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;
71 static struct wine_pthread_functions pthread_functions;
74 static RTL_CRITICAL_SECTION ldt_section;
75 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
78 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
79 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
81 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
82 static sigset_t ldt_sigset;
84 /***********************************************************************
85 * locking for LDT routines
87 static void ldt_lock(void)
91 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
92 RtlEnterCriticalSection( &ldt_section );
93 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
96 static void ldt_unlock(void)
98 if (ldt_section.RecursionCount == 1)
100 sigset_t sigset = ldt_sigset;
101 RtlLeaveCriticalSection( &ldt_section );
102 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
104 else RtlLeaveCriticalSection( &ldt_section );
108 /***********************************************************************
111 static inline NTSTATUS init_teb( TEB *teb )
113 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
115 teb->Tib.ExceptionList = (void *)~0UL;
116 teb->Tib.StackBase = (void *)~0UL;
117 teb->Tib.Self = &teb->Tib;
118 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
119 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
121 if (!(thread_data->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
122 thread_data->request_fd = -1;
123 thread_data->reply_fd = -1;
124 thread_data->wait_fd[0] = -1;
125 thread_data->wait_fd[1] = -1;
127 return STATUS_SUCCESS;
131 /***********************************************************************
134 * Make sure the unicode string doesn't point beyond the end pointer
136 static inline void fix_unicode_string( UNICODE_STRING *str, const char *end_ptr )
138 if ((char *)str->Buffer >= end_ptr)
140 str->Length = str->MaximumLength = 0;
144 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
146 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
148 if (str->Length >= str->MaximumLength)
150 if (str->MaximumLength >= sizeof(WCHAR))
151 str->Length = str->MaximumLength - sizeof(WCHAR);
153 str->Length = str->MaximumLength = 0;
158 /***********************************************************************
159 * init_user_process_params
161 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
163 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
168 RTL_USER_PROCESS_PARAMETERS *params = NULL;
170 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &info_size,
171 MEM_COMMIT, PAGE_READWRITE );
172 if (status != STATUS_SUCCESS) return status;
174 params->AllocationSize = info_size;
175 NtCurrentTeb()->Peb->ProcessParameters = params;
177 SERVER_START_REQ( get_startup_info )
179 wine_server_set_reply( req, params, info_size );
180 if (!(status = wine_server_call( req )))
182 info_size = wine_server_reply_size( reply );
183 *exe_file = wine_server_ptr_handle( reply->exe_file );
184 params->hStdInput = wine_server_ptr_handle( reply->hstdin );
185 params->hStdOutput = wine_server_ptr_handle( reply->hstdout );
186 params->hStdError = wine_server_ptr_handle( reply->hstderr );
190 if (status != STATUS_SUCCESS) return status;
192 if (params->Size > info_size) params->Size = info_size;
194 /* make sure the strings are valid */
195 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
196 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
197 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
198 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
199 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
200 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
201 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
202 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
204 /* environment needs to be a separate memory block */
205 env_size = info_size - params->Size;
206 if (!env_size) env_size = 1;
208 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
209 MEM_COMMIT, PAGE_READWRITE );
210 if (status != STATUS_SUCCESS) return status;
211 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
212 params->Environment = ptr;
214 RtlNormalizeProcessParams( params );
219 /***********************************************************************
222 * Setup the initial thread.
224 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
226 HANDLE thread_init(void)
231 SIZE_T size, info_size;
234 struct ntdll_thread_data *thread_data;
235 struct wine_pthread_thread_info thread_info;
236 static struct debug_info debug_info; /* debug info for initial thread */
240 /* reserve space for shared user data */
242 addr = (void *)0x7ffe0000;
244 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
245 user_shared_data = addr;
247 /* allocate and initialize the PEB */
251 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
252 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
255 peb->NumberOfProcessors = 1;
256 peb->ProcessParameters = ¶ms;
257 peb->TlsBitmap = &tls_bitmap;
258 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
259 peb->FlsBitmap = &fls_bitmap;
261 params.CurrentDirectory.DosPath.Buffer = current_dir;
262 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
263 params.wShowWindow = 1; /* SW_SHOWNORMAL */
264 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
265 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
266 sizeof(peb->TlsExpansionBitmapBits) * 8 );
267 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
268 InitializeListHead( &peb->FlsListHead );
269 InitializeListHead( &ldr.InLoadOrderModuleList );
270 InitializeListHead( &ldr.InMemoryOrderModuleList );
271 InitializeListHead( &ldr.InInitializationOrderModuleList );
272 InitializeListHead( &tls_links );
274 /* allocate and initialize the initial TEB */
276 sigstack_total_size = get_signal_stack_total_size();
277 while (1U << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
278 assert( 1U << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
279 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
280 thread_info.teb_size = sigstack_total_size;
283 size = sigstack_total_size;
284 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
285 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
288 thread_info.teb_size = size;
290 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
291 thread_data->debug_info = &debug_info;
292 InsertHeadList( &tls_links, &teb->TlsLinks );
294 thread_info.stack_base = NULL;
295 thread_info.stack_size = 0;
296 thread_info.teb_base = teb;
297 thread_info.teb_sel = thread_data->fs;
298 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
299 signal_init_thread( teb );
300 pthread_functions.init_thread( &thread_info );
301 virtual_init_threading();
303 debug_info.str_pos = debug_info.strings;
304 debug_info.out_pos = debug_info.output;
307 /* setup the server connection */
308 server_init_process();
309 info_size = server_init_thread( NULL );
311 /* create the process heap */
312 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
314 MESSAGE( "wine: failed to create the process heap\n" );
318 /* allocate user parameters */
321 init_user_process_params( info_size, &exe_file );
325 /* This is wine specific: we have no parent (we're started from unix)
326 * so, create a simple console with bare handles to unix stdio
328 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
329 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
330 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
333 /* initialize LDT locking */
334 wine_ldt_init_locking( ldt_lock, ldt_unlock );
336 /* initialize time values in user_shared_data */
337 NtQuerySystemTime( &now );
338 user_shared_data->SystemTime.LowPart = now.u.LowPart;
339 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
340 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
341 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
342 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
343 user_shared_data->TickCountMultiplier = 1 << 24;
350 /***********************************************************************
353 void abort_thread( int status )
355 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
356 close( ntdll_get_thread_data()->wait_fd[0] );
357 close( ntdll_get_thread_data()->wait_fd[1] );
358 close( ntdll_get_thread_data()->reply_fd );
359 close( ntdll_get_thread_data()->request_fd );
360 pthread_functions.abort_thread( status );
364 /***********************************************************************
367 static void DECLSPEC_NORETURN exit_thread( int status )
369 struct wine_pthread_thread_info info;
373 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
375 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
376 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
378 info.stack_base = NtCurrentTeb()->DeallocationStack;
379 info.teb_base = NtCurrentTeb();
380 info.teb_sel = wine_get_fs();
381 info.exit_status = status;
383 fds[0] = ntdll_get_thread_data()->wait_fd[0];
384 fds[1] = ntdll_get_thread_data()->wait_fd[1];
385 fds[2] = ntdll_get_thread_data()->reply_fd;
386 fds[3] = ntdll_get_thread_data()->request_fd;
387 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
389 info.stack_size = virtual_free_system_view( &info.stack_base );
390 info.teb_size = virtual_free_system_view( &info.teb_base );
396 pthread_functions.exit_thread( &info );
401 /* wrapper for apps that don't declare the thread function correctly */
402 extern DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg );
403 __ASM_GLOBAL_FUNC(call_thread_entry_point,
408 "movl 8(%ebp),%eax\n\t"
413 static inline DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg )
415 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)entry;
420 /***********************************************************************
423 * Hack to make things compatible with the thread procedures used by kernel32.CreateThread.
425 static void DECLSPEC_NORETURN call_thread_func( PRTL_THREAD_START_ROUTINE rtl_func, void *arg )
430 MODULE_DllThreadAttach( NULL );
433 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), rtl_func, arg );
435 exit_code = call_thread_entry_point( rtl_func, arg );
437 /* send the exit code to the server */
438 SERVER_START_REQ( terminate_thread )
440 req->handle = wine_server_obj_handle( GetCurrentThread() );
441 req->exit_code = exit_code;
442 wine_server_call( req );
449 LdrShutdownProcess();
455 exit_thread( exit_code );
460 /***********************************************************************
463 * Startup routine for a newly created thread.
465 static void start_thread( struct wine_pthread_thread_info *info )
467 TEB *teb = info->teb_base;
468 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
469 struct startup_info *startup_info = (struct startup_info *)info;
470 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
471 void *arg = startup_info->entry_arg;
472 struct debug_info debug_info;
474 debug_info.str_pos = debug_info.strings;
475 debug_info.out_pos = debug_info.output;
476 thread_data->debug_info = &debug_info;
478 signal_init_thread( teb );
479 server_init_thread( func );
480 pthread_functions.init_thread( info );
481 virtual_alloc_thread_stack( info->stack_base, info->stack_size );
482 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
485 InsertHeadList( &tls_links, &teb->TlsLinks );
488 /* NOTE: Windows does not have an exception handler around the call to
489 * the thread attach. We do for ease of debugging */
490 if (unhandled_exception_filter)
494 call_thread_func( func, arg );
496 __EXCEPT(unhandled_exception_filter)
498 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
503 call_thread_func( func, arg );
507 /***********************************************************************
508 * RtlCreateUserThread (NTDLL.@)
510 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
511 BOOLEAN suspended, PVOID stack_addr,
512 SIZE_T stack_reserve, SIZE_T stack_commit,
513 PRTL_THREAD_START_ROUTINE start, void *param,
514 HANDLE *handle_ptr, CLIENT_ID *id )
517 struct ntdll_thread_data *thread_data = NULL;
518 struct ntdll_thread_regs *thread_regs;
519 struct startup_info *info = NULL;
526 SIZE_T size, page_size = getpagesize();
528 if (process != NtCurrentProcess())
533 memset( &call, 0, sizeof(call) );
535 call.create_thread.type = APC_CREATE_THREAD;
536 call.create_thread.func = wine_server_client_ptr( start );
537 call.create_thread.arg = wine_server_client_ptr( param );
538 call.create_thread.reserve = stack_reserve;
539 call.create_thread.commit = stack_commit;
540 call.create_thread.suspend = suspended;
541 status = NTDLL_queue_process_apc( process, &call, &result );
542 if (status != STATUS_SUCCESS) return status;
544 if (result.create_thread.status == STATUS_SUCCESS)
546 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
547 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
548 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
550 return result.create_thread.status;
553 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
554 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
555 wine_server_send_fd( request_pipe[0] );
557 SERVER_START_REQ( new_thread )
559 req->access = THREAD_ALL_ACCESS;
560 req->attributes = 0; /* FIXME */
561 req->suspend = suspended;
562 req->request_fd = request_pipe[0];
563 if (!(status = wine_server_call( req )))
565 handle = wine_server_ptr_handle( reply->handle );
568 close( request_pipe[0] );
574 close( request_pipe[1] );
578 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
581 size = sigstack_total_size;
582 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
583 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
586 teb->Peb = NtCurrentTeb()->Peb;
587 info = (struct startup_info *)(teb + 1);
588 info->pthread_info.teb_size = size;
589 if ((status = init_teb( teb ))) goto error;
591 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
592 teb->ClientId.UniqueThread = ULongToHandle(tid);
594 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
595 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
596 thread_data->request_fd = request_pipe[1];
598 info->pthread_info.teb_base = teb;
599 info->pthread_info.teb_sel = thread_data->fs;
601 /* inherit debug registers from parent thread */
602 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
603 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
604 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
605 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
606 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
607 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
609 if (!stack_reserve || !stack_commit)
611 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
612 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
613 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
615 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
616 stack_reserve += page_size; /* for the guard page */
617 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
618 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
620 info->pthread_info.stack_base = NULL;
621 info->pthread_info.stack_size = stack_reserve;
622 info->pthread_info.entry = start_thread;
623 info->entry_point = start;
624 info->entry_arg = param;
626 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
628 status = STATUS_NO_MEMORY;
631 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
633 if (id) id->UniqueThread = ULongToHandle(tid);
634 if (handle_ptr) *handle_ptr = handle;
635 else NtClose( handle );
637 return STATUS_SUCCESS;
640 if (thread_data) wine_ldt_free_fs( thread_data->fs );
644 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
646 if (handle) NtClose( handle );
647 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
648 close( request_pipe[1] );
653 /***********************************************************************
654 * RtlExitUserThread (NTDLL.@)
656 void WINAPI RtlExitUserThread( ULONG status )
660 SERVER_START_REQ( terminate_thread )
662 /* send the exit code to the server */
663 req->handle = wine_server_obj_handle( GetCurrentThread() );
664 req->exit_code = status;
665 wine_server_call( req );
672 LdrShutdownProcess();
678 exit_thread( status );
683 /***********************************************************************
684 * NtOpenThread (NTDLL.@)
685 * ZwOpenThread (NTDLL.@)
687 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
688 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
692 SERVER_START_REQ( open_thread )
694 req->tid = HandleToULong(id->UniqueThread);
695 req->access = access;
696 req->attributes = attr ? attr->Attributes : 0;
697 ret = wine_server_call( req );
698 *handle = wine_server_ptr_handle( reply->handle );
705 /******************************************************************************
706 * NtSuspendThread (NTDLL.@)
707 * ZwSuspendThread (NTDLL.@)
709 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
713 SERVER_START_REQ( suspend_thread )
715 req->handle = wine_server_obj_handle( handle );
716 if (!(ret = wine_server_call( req ))) *count = reply->count;
723 /******************************************************************************
724 * NtResumeThread (NTDLL.@)
725 * ZwResumeThread (NTDLL.@)
727 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
731 SERVER_START_REQ( resume_thread )
733 req->handle = wine_server_obj_handle( handle );
734 if (!(ret = wine_server_call( req ))) *count = reply->count;
741 /******************************************************************************
742 * NtAlertResumeThread (NTDLL.@)
743 * ZwAlertResumeThread (NTDLL.@)
745 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
747 FIXME( "stub: should alert thread %p\n", handle );
748 return NtResumeThread( handle, count );
752 /******************************************************************************
753 * NtAlertThread (NTDLL.@)
754 * ZwAlertThread (NTDLL.@)
756 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
758 FIXME( "stub: %p\n", handle );
759 return STATUS_NOT_IMPLEMENTED;
763 /******************************************************************************
764 * NtTerminateThread (NTDLL.@)
765 * ZwTerminateThread (NTDLL.@)
767 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
772 SERVER_START_REQ( terminate_thread )
774 req->handle = wine_server_obj_handle( handle );
775 req->exit_code = exit_code;
776 ret = wine_server_call( req );
777 self = !ret && reply->self;
784 if (last) _exit( exit_code );
785 else abort_thread( exit_code );
791 /******************************************************************************
792 * NtQueueApcThread (NTDLL.@)
794 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
795 ULONG_PTR arg2, ULONG_PTR arg3 )
798 SERVER_START_REQ( queue_apc )
800 req->handle = wine_server_obj_handle( handle );
803 req->call.type = APC_USER;
804 req->call.user.func = wine_server_client_ptr( func );
805 req->call.user.args[0] = arg1;
806 req->call.user.args[1] = arg2;
807 req->call.user.args[2] = arg3;
809 else req->call.type = APC_NONE; /* wake up only */
810 ret = wine_server_call( req );
817 /***********************************************************************
818 * NtSetContextThread (NTDLL.@)
819 * ZwSetContextThread (NTDLL.@)
821 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
828 /* on i386 debug registers always require a server call */
829 self = (handle == GetCurrentThread());
830 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
832 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
833 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
834 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
835 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
841 SERVER_START_REQ( set_thread_context )
843 req->handle = wine_server_obj_handle( handle );
844 req->flags = context->ContextFlags;
846 wine_server_add_data( req, context, sizeof(*context) );
847 ret = wine_server_call( req );
852 if (ret == STATUS_PENDING)
854 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
856 for (i = 0; i < 100; i++)
858 SERVER_START_REQ( set_thread_context )
860 req->handle = wine_server_obj_handle( handle );
861 req->flags = context->ContextFlags;
863 wine_server_add_data( req, context, sizeof(*context) );
864 ret = wine_server_call( req );
867 if (ret == STATUS_PENDING)
869 LARGE_INTEGER timeout;
870 timeout.QuadPart = -10000;
871 NtDelayExecution( FALSE, &timeout );
875 NtResumeThread( handle, &dummy );
877 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
883 if (self) set_cpu_context( context );
884 return STATUS_SUCCESS;
888 /* copy a context structure according to the flags */
889 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
892 flags &= ~CONTEXT_i386; /* get rid of CPU id */
893 if (flags & CONTEXT_INTEGER)
902 if (flags & CONTEXT_CONTROL)
907 to->SegCs = from->SegCs;
908 to->SegSs = from->SegSs;
909 to->EFlags = from->EFlags;
911 if (flags & CONTEXT_SEGMENTS)
913 to->SegDs = from->SegDs;
914 to->SegEs = from->SegEs;
915 to->SegFs = from->SegFs;
916 to->SegGs = from->SegGs;
918 if (flags & CONTEXT_DEBUG_REGISTERS)
927 if (flags & CONTEXT_FLOATING_POINT)
929 to->FloatSave = from->FloatSave;
931 if (flags & CONTEXT_EXTENDED_REGISTERS)
933 memcpy( to->ExtendedRegisters, from->ExtendedRegisters, sizeof(to->ExtendedRegisters) );
935 #elif defined(__x86_64__)
936 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
937 if (flags & CONTEXT_CONTROL)
942 to->SegCs = from->SegCs;
943 to->SegSs = from->SegSs;
944 to->EFlags = from->EFlags;
945 to->MxCsr = from->MxCsr;
947 if (flags & CONTEXT_INTEGER)
964 if (flags & CONTEXT_SEGMENTS)
966 to->SegDs = from->SegDs;
967 to->SegEs = from->SegEs;
968 to->SegFs = from->SegFs;
969 to->SegGs = from->SegGs;
971 if (flags & CONTEXT_FLOATING_POINT)
973 to->u.FltSave = from->u.FltSave;
975 if (flags & CONTEXT_DEBUG_REGISTERS)
984 #elif defined(__sparc__)
985 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
986 if (flags & CONTEXT_CONTROL)
995 if (flags & CONTEXT_INTEGER)
1030 if (flags & CONTEXT_FLOATING_POINT)
1034 #elif defined(__powerpc__)
1036 if (flags & CONTEXT_CONTROL)
1038 to->Msr = from->Msr;
1039 to->Ctr = from->Ctr;
1040 to->Iar = from->Iar;
1042 if (flags & CONTEXT_INTEGER)
1044 to->Gpr0 = from->Gpr0;
1045 to->Gpr1 = from->Gpr1;
1046 to->Gpr2 = from->Gpr2;
1047 to->Gpr3 = from->Gpr3;
1048 to->Gpr4 = from->Gpr4;
1049 to->Gpr5 = from->Gpr5;
1050 to->Gpr6 = from->Gpr6;
1051 to->Gpr7 = from->Gpr7;
1052 to->Gpr8 = from->Gpr8;
1053 to->Gpr9 = from->Gpr9;
1054 to->Gpr10 = from->Gpr10;
1055 to->Gpr11 = from->Gpr11;
1056 to->Gpr12 = from->Gpr12;
1057 to->Gpr13 = from->Gpr13;
1058 to->Gpr14 = from->Gpr14;
1059 to->Gpr15 = from->Gpr15;
1060 to->Gpr16 = from->Gpr16;
1061 to->Gpr17 = from->Gpr17;
1062 to->Gpr18 = from->Gpr18;
1063 to->Gpr19 = from->Gpr19;
1064 to->Gpr20 = from->Gpr20;
1065 to->Gpr21 = from->Gpr21;
1066 to->Gpr22 = from->Gpr22;
1067 to->Gpr23 = from->Gpr23;
1068 to->Gpr24 = from->Gpr24;
1069 to->Gpr25 = from->Gpr25;
1070 to->Gpr26 = from->Gpr26;
1071 to->Gpr27 = from->Gpr27;
1072 to->Gpr28 = from->Gpr28;
1073 to->Gpr29 = from->Gpr29;
1074 to->Gpr30 = from->Gpr30;
1075 to->Gpr31 = from->Gpr31;
1076 to->Xer = from->Xer;
1079 if (flags & CONTEXT_FLOATING_POINT)
1081 to->Fpr0 = from->Fpr0;
1082 to->Fpr1 = from->Fpr1;
1083 to->Fpr2 = from->Fpr2;
1084 to->Fpr3 = from->Fpr3;
1085 to->Fpr4 = from->Fpr4;
1086 to->Fpr5 = from->Fpr5;
1087 to->Fpr6 = from->Fpr6;
1088 to->Fpr7 = from->Fpr7;
1089 to->Fpr8 = from->Fpr8;
1090 to->Fpr9 = from->Fpr9;
1091 to->Fpr10 = from->Fpr10;
1092 to->Fpr11 = from->Fpr11;
1093 to->Fpr12 = from->Fpr12;
1094 to->Fpr13 = from->Fpr13;
1095 to->Fpr14 = from->Fpr14;
1096 to->Fpr15 = from->Fpr15;
1097 to->Fpr16 = from->Fpr16;
1098 to->Fpr17 = from->Fpr17;
1099 to->Fpr18 = from->Fpr18;
1100 to->Fpr19 = from->Fpr19;
1101 to->Fpr20 = from->Fpr20;
1102 to->Fpr21 = from->Fpr21;
1103 to->Fpr22 = from->Fpr22;
1104 to->Fpr23 = from->Fpr23;
1105 to->Fpr24 = from->Fpr24;
1106 to->Fpr25 = from->Fpr25;
1107 to->Fpr26 = from->Fpr26;
1108 to->Fpr27 = from->Fpr27;
1109 to->Fpr28 = from->Fpr28;
1110 to->Fpr29 = from->Fpr29;
1111 to->Fpr30 = from->Fpr30;
1112 to->Fpr31 = from->Fpr31;
1113 to->Fpscr = from->Fpscr;
1116 #error You must implement context copying for your CPU
1121 /***********************************************************************
1122 * NtGetContextThread (NTDLL.@)
1123 * ZwGetContextThread (NTDLL.@)
1125 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1130 DWORD needed_flags = context->ContextFlags;
1131 BOOL self = (handle == GetCurrentThread());
1134 /* on i386 debug registers always require a server call */
1135 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1140 SERVER_START_REQ( get_thread_context )
1142 req->handle = wine_server_obj_handle( handle );
1143 req->flags = context->ContextFlags;
1145 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1146 ret = wine_server_call( req );
1151 if (ret == STATUS_PENDING)
1153 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1155 for (i = 0; i < 100; i++)
1157 SERVER_START_REQ( get_thread_context )
1159 req->handle = wine_server_obj_handle( handle );
1160 req->flags = context->ContextFlags;
1162 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1163 ret = wine_server_call( req );
1166 if (ret == STATUS_PENDING)
1168 LARGE_INTEGER timeout;
1169 timeout.QuadPart = -10000;
1170 NtDelayExecution( FALSE, &timeout );
1174 NtResumeThread( handle, &dummy );
1176 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1178 if (ret) return ret;
1179 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1180 needed_flags &= ~ctx.ContextFlags;
1187 RtlCaptureContext( &ctx );
1188 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1191 /* update the cached version of the debug registers */
1192 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1194 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1195 regs->dr0 = context->Dr0;
1196 regs->dr1 = context->Dr1;
1197 regs->dr2 = context->Dr2;
1198 regs->dr3 = context->Dr3;
1199 regs->dr6 = context->Dr6;
1200 regs->dr7 = context->Dr7;
1204 return STATUS_SUCCESS;
1208 /******************************************************************************
1209 * NtQueryInformationThread (NTDLL.@)
1210 * ZwQueryInformationThread (NTDLL.@)
1212 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1213 void *data, ULONG length, ULONG *ret_len )
1219 case ThreadBasicInformation:
1221 THREAD_BASIC_INFORMATION info;
1222 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1224 SERVER_START_REQ( get_thread_info )
1226 req->handle = wine_server_obj_handle( handle );
1228 if (!(status = wine_server_call( req )))
1230 info.ExitStatus = reply->exit_code;
1231 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
1232 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
1233 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
1234 info.AffinityMask = reply->affinity & affinity_mask;
1235 info.Priority = reply->priority;
1236 info.BasePriority = reply->priority; /* FIXME */
1240 if (status == STATUS_SUCCESS)
1242 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1243 if (ret_len) *ret_len = min( length, sizeof(info) );
1247 case ThreadAffinityMask:
1249 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1250 ULONG_PTR affinity = 0;
1252 SERVER_START_REQ( get_thread_info )
1254 req->handle = wine_server_obj_handle( handle );
1256 if (!(status = wine_server_call( req )))
1257 affinity = reply->affinity & affinity_mask;
1260 if (status == STATUS_SUCCESS)
1262 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
1263 if (ret_len) *ret_len = min( length, sizeof(affinity) );
1269 KERNEL_USER_TIMES kusrt;
1270 /* We need to do a server call to get the creation time or exit time */
1271 /* This works on any thread */
1272 SERVER_START_REQ( get_thread_info )
1274 req->handle = wine_server_obj_handle( handle );
1276 status = wine_server_call( req );
1277 if (status == STATUS_SUCCESS)
1279 kusrt.CreateTime.QuadPart = reply->creation_time;
1280 kusrt.ExitTime.QuadPart = reply->exit_time;
1284 if (status == STATUS_SUCCESS)
1286 /* We call times(2) for kernel time or user time */
1287 /* We can only (portably) do this for the current thread */
1288 if (handle == GetCurrentThread())
1290 struct tms time_buf;
1291 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1294 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1295 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1299 static BOOL reported = FALSE;
1301 kusrt.KernelTime.QuadPart = 0;
1302 kusrt.UserTime.QuadPart = 0;
1304 TRACE("Cannot get kerneltime or usertime of other threads\n");
1307 FIXME("Cannot get kerneltime or usertime of other threads\n");
1311 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1312 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1316 case ThreadDescriptorTableEntry:
1319 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1320 if (length < sizeof(*tdi))
1321 status = STATUS_INFO_LENGTH_MISMATCH;
1322 else if (!(tdi->Selector & 4)) /* GDT selector */
1324 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1325 status = STATUS_SUCCESS;
1326 if (!sel) /* null selector */
1327 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1330 tdi->Entry.BaseLow = 0;
1331 tdi->Entry.HighWord.Bits.BaseMid = 0;
1332 tdi->Entry.HighWord.Bits.BaseHi = 0;
1333 tdi->Entry.LimitLow = 0xffff;
1334 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1335 tdi->Entry.HighWord.Bits.Dpl = 3;
1336 tdi->Entry.HighWord.Bits.Sys = 0;
1337 tdi->Entry.HighWord.Bits.Pres = 1;
1338 tdi->Entry.HighWord.Bits.Granularity = 1;
1339 tdi->Entry.HighWord.Bits.Default_Big = 1;
1340 tdi->Entry.HighWord.Bits.Type = 0x12;
1341 /* it has to be one of the system GDT selectors */
1342 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1344 if (sel == (wine_get_cs() & ~3))
1345 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1346 else status = STATUS_ACCESS_DENIED;
1352 SERVER_START_REQ( get_selector_entry )
1354 req->handle = wine_server_obj_handle( handle );
1355 req->entry = tdi->Selector >> 3;
1356 status = wine_server_call( req );
1359 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1360 status = STATUS_ACCESS_VIOLATION;
1363 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1364 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1365 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1371 if (status == STATUS_SUCCESS && ret_len)
1372 /* yes, that's a bit strange, but it's the way it is */
1373 *ret_len = sizeof(LDT_ENTRY);
1375 status = STATUS_NOT_IMPLEMENTED;
1379 case ThreadAmILastThread:
1381 SERVER_START_REQ(get_thread_info)
1383 req->handle = wine_server_obj_handle( handle );
1385 status = wine_server_call( req );
1386 if (status == STATUS_SUCCESS)
1388 BOOLEAN last = reply->last;
1389 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1390 if (ret_len) *ret_len = min( length, sizeof(last) );
1396 case ThreadPriority:
1397 case ThreadBasePriority:
1398 case ThreadImpersonationToken:
1399 case ThreadEnableAlignmentFaultFixup:
1400 case ThreadEventPair_Reusable:
1401 case ThreadQuerySetWin32StartAddress:
1402 case ThreadZeroTlsCell:
1403 case ThreadPerformanceCount:
1404 case ThreadIdealProcessor:
1405 case ThreadPriorityBoost:
1406 case ThreadSetTlsArrayAddress:
1407 case ThreadIsIoPending:
1409 FIXME( "info class %d not supported yet\n", class );
1410 return STATUS_NOT_IMPLEMENTED;
1415 /******************************************************************************
1416 * NtSetInformationThread (NTDLL.@)
1417 * ZwSetInformationThread (NTDLL.@)
1419 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1420 LPCVOID data, ULONG length )
1425 case ThreadZeroTlsCell:
1426 if (handle == GetCurrentThread())
1431 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1432 index = *(const DWORD *)data;
1433 if (index < TLS_MINIMUM_AVAILABLE)
1435 RtlAcquirePebLock();
1436 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1438 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1439 teb->TlsSlots[index] = 0;
1441 RtlReleasePebLock();
1445 index -= TLS_MINIMUM_AVAILABLE;
1446 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1447 return STATUS_INVALID_PARAMETER;
1448 RtlAcquirePebLock();
1449 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1451 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1452 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1454 RtlReleasePebLock();
1456 return STATUS_SUCCESS;
1458 FIXME( "ZeroTlsCell not supported on other threads\n" );
1459 return STATUS_NOT_IMPLEMENTED;
1461 case ThreadImpersonationToken:
1463 const HANDLE *phToken = data;
1464 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1465 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1466 SERVER_START_REQ( set_thread_info )
1468 req->handle = wine_server_obj_handle( handle );
1469 req->token = wine_server_obj_handle( *phToken );
1470 req->mask = SET_THREAD_INFO_TOKEN;
1471 status = wine_server_call( req );
1476 case ThreadBasePriority:
1478 const DWORD *pprio = data;
1479 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1480 SERVER_START_REQ( set_thread_info )
1482 req->handle = wine_server_obj_handle( handle );
1483 req->priority = *pprio;
1484 req->mask = SET_THREAD_INFO_PRIORITY;
1485 status = wine_server_call( req );
1490 case ThreadAffinityMask:
1492 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1493 const ULONG_PTR *paff = data;
1494 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1495 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1496 SERVER_START_REQ( set_thread_info )
1498 req->handle = wine_server_obj_handle( handle );
1499 req->affinity = *paff;
1500 req->mask = SET_THREAD_INFO_AFFINITY;
1501 status = wine_server_call( req );
1506 case ThreadBasicInformation:
1508 case ThreadPriority:
1509 case ThreadDescriptorTableEntry:
1510 case ThreadEnableAlignmentFaultFixup:
1511 case ThreadEventPair_Reusable:
1512 case ThreadQuerySetWin32StartAddress:
1513 case ThreadPerformanceCount:
1514 case ThreadAmILastThread:
1515 case ThreadIdealProcessor:
1516 case ThreadPriorityBoost:
1517 case ThreadSetTlsArrayAddress:
1518 case ThreadIsIoPending:
1520 FIXME( "info class %d not supported yet\n", class );
1521 return STATUS_NOT_IMPLEMENTED;