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/debug.h"
41 #include "ntdll_misc.h"
43 #include "wine/exception.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(thread);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
48 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
50 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
52 /* info passed to a starting thread */
56 PRTL_THREAD_START_ROUTINE entry_point;
60 static PEB_LDR_DATA ldr;
61 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
62 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
63 static RTL_BITMAP tls_bitmap;
64 static RTL_BITMAP tls_expansion_bitmap;
65 static RTL_BITMAP fls_bitmap;
66 static LIST_ENTRY tls_links;
67 static int nb_threads = 1;
69 static RTL_CRITICAL_SECTION ldt_section;
70 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
73 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
74 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
76 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
77 static sigset_t ldt_sigset;
79 /***********************************************************************
80 * locking for LDT routines
82 static void ldt_lock(void)
86 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
87 RtlEnterCriticalSection( &ldt_section );
88 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
91 static void ldt_unlock(void)
93 if (ldt_section.RecursionCount == 1)
95 sigset_t sigset = ldt_sigset;
96 RtlLeaveCriticalSection( &ldt_section );
97 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
99 else RtlLeaveCriticalSection( &ldt_section );
103 /***********************************************************************
106 * Copy a unicode string from the startup info.
108 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
112 str->MaximumLength = len + sizeof(WCHAR);
113 memcpy( str->Buffer, *src, len );
114 str->Buffer[len / sizeof(WCHAR)] = 0;
115 *src += len / sizeof(WCHAR);
116 *dst += len / sizeof(WCHAR) + 1;
119 /***********************************************************************
120 * init_user_process_params
122 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
124 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
128 SIZE_T info_size, env_size, size, alloc_size;
130 startup_info_t *info;
131 RTL_USER_PROCESS_PARAMETERS *params = NULL;
133 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
134 return STATUS_NO_MEMORY;
136 SERVER_START_REQ( get_startup_info )
138 wine_server_set_reply( req, info, data_size );
139 if (!(status = wine_server_call( req )))
141 data_size = wine_server_reply_size( reply );
142 info_size = reply->info_size;
143 env_size = data_size - info_size;
144 *exe_file = wine_server_ptr_handle( reply->exe_file );
148 if (status != STATUS_SUCCESS) goto done;
150 size = sizeof(*params);
151 size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
152 size += info->dllpath_len + sizeof(WCHAR);
153 size += info->imagepath_len + sizeof(WCHAR);
154 size += info->cmdline_len + sizeof(WCHAR);
155 size += info->title_len + sizeof(WCHAR);
156 size += info->desktop_len + sizeof(WCHAR);
157 size += info->shellinfo_len + sizeof(WCHAR);
158 size += info->runtime_len + sizeof(WCHAR);
161 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &alloc_size,
162 MEM_COMMIT, PAGE_READWRITE );
163 if (status != STATUS_SUCCESS) goto done;
165 NtCurrentTeb()->Peb->ProcessParameters = params;
166 params->AllocationSize = alloc_size;
168 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
169 params->DebugFlags = info->debug_flags;
170 params->ConsoleHandle = wine_server_ptr_handle( info->console );
171 params->ConsoleFlags = info->console_flags;
172 params->hStdInput = wine_server_ptr_handle( info->hstdin );
173 params->hStdOutput = wine_server_ptr_handle( info->hstdout );
174 params->hStdError = wine_server_ptr_handle( info->hstderr );
175 params->dwX = info->x;
176 params->dwY = info->y;
177 params->dwXSize = info->xsize;
178 params->dwYSize = info->ysize;
179 params->dwXCountChars = info->xchars;
180 params->dwYCountChars = info->ychars;
181 params->dwFillAttribute = info->attribute;
182 params->dwFlags = info->flags;
183 params->wShowWindow = info->show;
185 src = (WCHAR *)(info + 1);
186 dst = (WCHAR *)(params + 1);
188 /* current directory needs more space */
189 get_unicode_string( ¶ms->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
190 params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
191 dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
193 get_unicode_string( ¶ms->DllPath, &src, &dst, info->dllpath_len );
194 get_unicode_string( ¶ms->ImagePathName, &src, &dst, info->imagepath_len );
195 get_unicode_string( ¶ms->CommandLine, &src, &dst, info->cmdline_len );
196 get_unicode_string( ¶ms->WindowTitle, &src, &dst, info->title_len );
197 get_unicode_string( ¶ms->Desktop, &src, &dst, info->desktop_len );
198 get_unicode_string( ¶ms->ShellInfo, &src, &dst, info->shellinfo_len );
200 /* runtime info isn't a real string */
201 params->RuntimeInfo.Buffer = dst;
202 params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
203 memcpy( dst, src, info->runtime_len );
205 /* environment needs to be a separate memory block */
207 alloc_size = max( 1, env_size );
208 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
209 MEM_COMMIT, PAGE_READWRITE );
210 if (status != STATUS_SUCCESS) goto done;
211 memcpy( ptr, (char *)info + info_size, env_size );
212 params->Environment = ptr;
215 RtlFreeHeap( GetProcessHeap(), 0, info );
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 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->ProcessParameters = ¶ms;
256 peb->TlsBitmap = &tls_bitmap;
257 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
258 peb->FlsBitmap = &fls_bitmap;
260 params.CurrentDirectory.DosPath.Buffer = current_dir;
261 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
262 params.wShowWindow = 1; /* SW_SHOWNORMAL */
263 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
264 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
265 sizeof(peb->TlsExpansionBitmapBits) * 8 );
266 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
267 InitializeListHead( &peb->FlsListHead );
268 InitializeListHead( &ldr.InLoadOrderModuleList );
269 InitializeListHead( &ldr.InMemoryOrderModuleList );
270 InitializeListHead( &ldr.InInitializationOrderModuleList );
271 InitializeListHead( &tls_links );
273 /* allocate and initialize the initial TEB */
275 signal_alloc_thread( &teb );
277 teb->Tib.StackBase = (void *)~0UL;
278 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
279 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
281 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
282 thread_data->request_fd = -1;
283 thread_data->reply_fd = -1;
284 thread_data->wait_fd[0] = -1;
285 thread_data->wait_fd[1] = -1;
286 thread_data->debug_info = &debug_info;
287 InsertHeadList( &tls_links, &teb->TlsLinks );
289 signal_init_thread( teb );
290 virtual_init_threading();
292 debug_info.str_pos = debug_info.strings;
293 debug_info.out_pos = debug_info.output;
296 /* setup the server connection */
297 server_init_process();
298 info_size = server_init_thread( peb );
300 /* create the process heap */
301 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
303 MESSAGE( "wine: failed to create the process heap\n" );
307 /* allocate user parameters */
310 init_user_process_params( info_size, &exe_file );
314 /* This is wine specific: we have no parent (we're started from unix)
315 * so, create a simple console with bare handles to unix stdio
317 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
318 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
319 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
322 /* initialize LDT locking */
323 wine_ldt_init_locking( ldt_lock, ldt_unlock );
325 /* initialize time values in user_shared_data */
326 NtQuerySystemTime( &now );
327 user_shared_data->SystemTime.LowPart = now.u.LowPart;
328 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
329 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
330 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
331 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
332 user_shared_data->TickCountMultiplier = 1 << 24;
340 /***********************************************************************
343 void terminate_thread( int status )
345 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
346 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
348 close( ntdll_get_thread_data()->wait_fd[0] );
349 close( ntdll_get_thread_data()->wait_fd[1] );
350 close( ntdll_get_thread_data()->reply_fd );
351 close( ntdll_get_thread_data()->request_fd );
352 pthread_exit( UIntToPtr(status) );
356 /***********************************************************************
359 void exit_thread( int status )
361 static void *prev_teb;
364 if (status) /* send the exit code to the server (0 is already the default) */
366 SERVER_START_REQ( terminate_thread )
368 req->handle = wine_server_obj_handle( GetCurrentThread() );
369 req->exit_code = status;
370 wine_server_call( req );
375 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
377 LdrShutdownProcess();
383 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
385 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
386 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
388 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
390 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
392 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
394 pthread_join( thread_data->pthread_id, NULL );
395 signal_free_thread( teb );
398 close( ntdll_get_thread_data()->wait_fd[0] );
399 close( ntdll_get_thread_data()->wait_fd[1] );
400 close( ntdll_get_thread_data()->reply_fd );
401 close( ntdll_get_thread_data()->request_fd );
402 pthread_exit( UIntToPtr(status) );
406 /***********************************************************************
409 * Startup routine for a newly created thread.
411 static void start_thread( struct startup_info *info )
413 TEB *teb = info->teb;
414 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
415 PRTL_THREAD_START_ROUTINE func = info->entry_point;
416 void *arg = info->entry_arg;
417 struct debug_info debug_info;
419 debug_info.str_pos = debug_info.strings;
420 debug_info.out_pos = debug_info.output;
421 thread_data->debug_info = &debug_info;
422 thread_data->pthread_id = pthread_self();
424 signal_init_thread( teb );
425 server_init_thread( func );
426 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
429 InsertHeadList( &tls_links, &teb->TlsLinks );
432 MODULE_DllThreadAttach( NULL );
435 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
437 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
441 /***********************************************************************
442 * RtlCreateUserThread (NTDLL.@)
444 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
445 BOOLEAN suspended, PVOID stack_addr,
446 SIZE_T stack_reserve, SIZE_T stack_commit,
447 PRTL_THREAD_START_ROUTINE start, void *param,
448 HANDLE *handle_ptr, CLIENT_ID *id )
451 pthread_t pthread_id;
453 struct ntdll_thread_data *thread_data;
454 struct startup_info *info = NULL;
461 if (process != NtCurrentProcess())
466 memset( &call, 0, sizeof(call) );
468 call.create_thread.type = APC_CREATE_THREAD;
469 call.create_thread.func = wine_server_client_ptr( start );
470 call.create_thread.arg = wine_server_client_ptr( param );
471 call.create_thread.reserve = stack_reserve;
472 call.create_thread.commit = stack_commit;
473 call.create_thread.suspend = suspended;
474 status = NTDLL_queue_process_apc( process, &call, &result );
475 if (status != STATUS_SUCCESS) return status;
477 if (result.create_thread.status == STATUS_SUCCESS)
479 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
480 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
481 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
483 return result.create_thread.status;
486 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
487 wine_server_send_fd( request_pipe[0] );
489 SERVER_START_REQ( new_thread )
491 req->access = THREAD_ALL_ACCESS;
492 req->attributes = 0; /* FIXME */
493 req->suspend = suspended;
494 req->request_fd = request_pipe[0];
495 if (!(status = wine_server_call( req )))
497 handle = wine_server_ptr_handle( reply->handle );
500 close( request_pipe[0] );
506 close( request_pipe[1] );
510 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
512 if ((status = signal_alloc_thread( &teb ))) goto error;
514 teb->Peb = NtCurrentTeb()->Peb;
515 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
516 teb->ClientId.UniqueThread = ULongToHandle(tid);
517 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
518 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
520 info = (struct startup_info *)(teb + 1);
522 info->entry_point = start;
523 info->entry_arg = param;
525 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
526 thread_data->request_fd = request_pipe[1];
527 thread_data->reply_fd = -1;
528 thread_data->wait_fd[0] = -1;
529 thread_data->wait_fd[1] = -1;
531 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
533 pthread_attr_init( &attr );
534 pthread_attr_setstack( &attr, teb->DeallocationStack,
535 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
536 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
537 interlocked_xchg_add( &nb_threads, 1 );
538 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
540 interlocked_xchg_add( &nb_threads, -1 );
541 pthread_attr_destroy( &attr );
542 status = STATUS_NO_MEMORY;
545 pthread_attr_destroy( &attr );
546 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
548 if (id) id->UniqueThread = ULongToHandle(tid);
549 if (handle_ptr) *handle_ptr = handle;
550 else NtClose( handle );
552 return STATUS_SUCCESS;
555 if (teb) signal_free_thread( teb );
556 if (handle) NtClose( handle );
557 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
558 close( request_pipe[1] );
563 /***********************************************************************
564 * NtOpenThread (NTDLL.@)
565 * ZwOpenThread (NTDLL.@)
567 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
568 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
572 SERVER_START_REQ( open_thread )
574 req->tid = HandleToULong(id->UniqueThread);
575 req->access = access;
576 req->attributes = attr ? attr->Attributes : 0;
577 ret = wine_server_call( req );
578 *handle = wine_server_ptr_handle( reply->handle );
585 /******************************************************************************
586 * NtSuspendThread (NTDLL.@)
587 * ZwSuspendThread (NTDLL.@)
589 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
593 SERVER_START_REQ( suspend_thread )
595 req->handle = wine_server_obj_handle( handle );
596 if (!(ret = wine_server_call( req ))) *count = reply->count;
603 /******************************************************************************
604 * NtResumeThread (NTDLL.@)
605 * ZwResumeThread (NTDLL.@)
607 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
611 SERVER_START_REQ( resume_thread )
613 req->handle = wine_server_obj_handle( handle );
614 if (!(ret = wine_server_call( req ))) *count = reply->count;
621 /******************************************************************************
622 * NtAlertResumeThread (NTDLL.@)
623 * ZwAlertResumeThread (NTDLL.@)
625 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
627 FIXME( "stub: should alert thread %p\n", handle );
628 return NtResumeThread( handle, count );
632 /******************************************************************************
633 * NtAlertThread (NTDLL.@)
634 * ZwAlertThread (NTDLL.@)
636 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
638 FIXME( "stub: %p\n", handle );
639 return STATUS_NOT_IMPLEMENTED;
643 /******************************************************************************
644 * NtTerminateThread (NTDLL.@)
645 * ZwTerminateThread (NTDLL.@)
647 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
652 SERVER_START_REQ( terminate_thread )
654 req->handle = wine_server_obj_handle( handle );
655 req->exit_code = exit_code;
656 ret = wine_server_call( req );
657 self = !ret && reply->self;
661 if (self) abort_thread( exit_code );
666 /******************************************************************************
667 * NtQueueApcThread (NTDLL.@)
669 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
670 ULONG_PTR arg2, ULONG_PTR arg3 )
673 SERVER_START_REQ( queue_apc )
675 req->handle = wine_server_obj_handle( handle );
678 req->call.type = APC_USER;
679 req->call.user.func = wine_server_client_ptr( func );
680 req->call.user.args[0] = arg1;
681 req->call.user.args[1] = arg2;
682 req->call.user.args[2] = arg3;
684 else req->call.type = APC_NONE; /* wake up only */
685 ret = wine_server_call( req );
692 /***********************************************************************
693 * NtSetContextThread (NTDLL.@)
694 * ZwSetContextThread (NTDLL.@)
696 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
703 /* on i386 debug registers always require a server call */
704 self = (handle == GetCurrentThread());
705 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
707 self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
708 ntdll_get_thread_data()->dr1 == context->Dr1 &&
709 ntdll_get_thread_data()->dr2 == context->Dr2 &&
710 ntdll_get_thread_data()->dr3 == context->Dr3 &&
711 ntdll_get_thread_data()->dr6 == context->Dr6 &&
712 ntdll_get_thread_data()->dr7 == context->Dr7);
718 context_t server_context;
720 context_to_server( &server_context, context );
722 SERVER_START_REQ( set_thread_context )
724 req->handle = wine_server_obj_handle( handle );
726 wine_server_add_data( req, &server_context, sizeof(server_context) );
727 ret = wine_server_call( req );
732 if (ret == STATUS_PENDING)
734 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
736 for (i = 0; i < 100; i++)
738 SERVER_START_REQ( set_thread_context )
740 req->handle = wine_server_obj_handle( handle );
742 wine_server_add_data( req, &server_context, sizeof(server_context) );
743 ret = wine_server_call( req );
746 if (ret == STATUS_PENDING)
748 LARGE_INTEGER timeout;
749 timeout.QuadPart = -10000;
750 NtDelayExecution( FALSE, &timeout );
754 NtResumeThread( handle, &dummy );
756 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
762 if (self) set_cpu_context( context );
763 return STATUS_SUCCESS;
767 /* convert CPU-specific flags to generic server flags */
768 static inline unsigned int get_server_context_flags( DWORD flags )
770 unsigned int ret = 0;
772 flags &= 0x3f; /* mask CPU id flags */
773 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
774 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
775 #ifdef CONTEXT_SEGMENTS
776 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
778 #ifdef CONTEXT_FLOATING_POINT
779 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
781 #ifdef CONTEXT_DEBUG_REGISTERS
782 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
784 #ifdef CONTEXT_EXTENDED_REGISTERS
785 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
790 /***********************************************************************
791 * NtGetContextThread (NTDLL.@)
792 * ZwGetContextThread (NTDLL.@)
794 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
798 DWORD needed_flags = context->ContextFlags;
799 BOOL self = (handle == GetCurrentThread());
802 /* on i386 debug registers always require a server call */
803 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
808 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
809 context_t server_context;
811 SERVER_START_REQ( get_thread_context )
813 req->handle = wine_server_obj_handle( handle );
814 req->flags = server_flags;
816 wine_server_set_reply( req, &server_context, sizeof(server_context) );
817 ret = wine_server_call( req );
822 if (ret == STATUS_PENDING)
824 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
826 for (i = 0; i < 100; i++)
828 SERVER_START_REQ( get_thread_context )
830 req->handle = wine_server_obj_handle( handle );
831 req->flags = server_flags;
833 wine_server_set_reply( req, &server_context, sizeof(server_context) );
834 ret = wine_server_call( req );
837 if (ret == STATUS_PENDING)
839 LARGE_INTEGER timeout;
840 timeout.QuadPart = -10000;
841 NtDelayExecution( FALSE, &timeout );
845 NtResumeThread( handle, &dummy );
847 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
849 if (!ret) ret = context_from_server( context, &server_context );
851 needed_flags &= ~context->ContextFlags;
859 RtlCaptureContext( &ctx );
860 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
861 context->ContextFlags |= ctx.ContextFlags & needed_flags;
864 /* update the cached version of the debug registers */
865 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
867 ntdll_get_thread_data()->dr0 = context->Dr0;
868 ntdll_get_thread_data()->dr1 = context->Dr1;
869 ntdll_get_thread_data()->dr2 = context->Dr2;
870 ntdll_get_thread_data()->dr3 = context->Dr3;
871 ntdll_get_thread_data()->dr6 = context->Dr6;
872 ntdll_get_thread_data()->dr7 = context->Dr7;
876 return STATUS_SUCCESS;
880 /******************************************************************************
881 * NtQueryInformationThread (NTDLL.@)
882 * ZwQueryInformationThread (NTDLL.@)
884 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
885 void *data, ULONG length, ULONG *ret_len )
891 case ThreadBasicInformation:
893 THREAD_BASIC_INFORMATION info;
894 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
896 SERVER_START_REQ( get_thread_info )
898 req->handle = wine_server_obj_handle( handle );
900 if (!(status = wine_server_call( req )))
902 info.ExitStatus = reply->exit_code;
903 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
904 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
905 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
906 info.AffinityMask = reply->affinity & affinity_mask;
907 info.Priority = reply->priority;
908 info.BasePriority = reply->priority; /* FIXME */
912 if (status == STATUS_SUCCESS)
914 if (data) memcpy( data, &info, min( length, sizeof(info) ));
915 if (ret_len) *ret_len = min( length, sizeof(info) );
919 case ThreadAffinityMask:
921 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
922 ULONG_PTR affinity = 0;
924 SERVER_START_REQ( get_thread_info )
926 req->handle = wine_server_obj_handle( handle );
928 if (!(status = wine_server_call( req )))
929 affinity = reply->affinity & affinity_mask;
932 if (status == STATUS_SUCCESS)
934 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
935 if (ret_len) *ret_len = min( length, sizeof(affinity) );
941 KERNEL_USER_TIMES kusrt;
942 /* We need to do a server call to get the creation time or exit time */
943 /* This works on any thread */
944 SERVER_START_REQ( get_thread_info )
946 req->handle = wine_server_obj_handle( handle );
948 status = wine_server_call( req );
949 if (status == STATUS_SUCCESS)
951 kusrt.CreateTime.QuadPart = reply->creation_time;
952 kusrt.ExitTime.QuadPart = reply->exit_time;
956 if (status == STATUS_SUCCESS)
958 /* We call times(2) for kernel time or user time */
959 /* We can only (portably) do this for the current thread */
960 if (handle == GetCurrentThread())
963 long clocks_per_sec = sysconf(_SC_CLK_TCK);
966 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
967 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
971 static BOOL reported = FALSE;
973 kusrt.KernelTime.QuadPart = 0;
974 kusrt.UserTime.QuadPart = 0;
976 TRACE("Cannot get kerneltime or usertime of other threads\n");
979 FIXME("Cannot get kerneltime or usertime of other threads\n");
983 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
984 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
988 case ThreadDescriptorTableEntry:
991 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
992 if (length < sizeof(*tdi))
993 status = STATUS_INFO_LENGTH_MISMATCH;
994 else if (!(tdi->Selector & 4)) /* GDT selector */
996 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
997 status = STATUS_SUCCESS;
998 if (!sel) /* null selector */
999 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1002 tdi->Entry.BaseLow = 0;
1003 tdi->Entry.HighWord.Bits.BaseMid = 0;
1004 tdi->Entry.HighWord.Bits.BaseHi = 0;
1005 tdi->Entry.LimitLow = 0xffff;
1006 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1007 tdi->Entry.HighWord.Bits.Dpl = 3;
1008 tdi->Entry.HighWord.Bits.Sys = 0;
1009 tdi->Entry.HighWord.Bits.Pres = 1;
1010 tdi->Entry.HighWord.Bits.Granularity = 1;
1011 tdi->Entry.HighWord.Bits.Default_Big = 1;
1012 tdi->Entry.HighWord.Bits.Type = 0x12;
1013 /* it has to be one of the system GDT selectors */
1014 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1016 if (sel == (wine_get_cs() & ~3))
1017 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1018 else status = STATUS_ACCESS_DENIED;
1024 SERVER_START_REQ( get_selector_entry )
1026 req->handle = wine_server_obj_handle( handle );
1027 req->entry = tdi->Selector >> 3;
1028 status = wine_server_call( req );
1031 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1032 status = STATUS_ACCESS_VIOLATION;
1035 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1036 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1037 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1043 if (status == STATUS_SUCCESS && ret_len)
1044 /* yes, that's a bit strange, but it's the way it is */
1045 *ret_len = sizeof(LDT_ENTRY);
1047 status = STATUS_NOT_IMPLEMENTED;
1051 case ThreadAmILastThread:
1053 SERVER_START_REQ(get_thread_info)
1055 req->handle = wine_server_obj_handle( handle );
1057 status = wine_server_call( req );
1058 if (status == STATUS_SUCCESS)
1060 BOOLEAN last = reply->last;
1061 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1062 if (ret_len) *ret_len = min( length, sizeof(last) );
1068 case ThreadPriority:
1069 case ThreadBasePriority:
1070 case ThreadImpersonationToken:
1071 case ThreadEnableAlignmentFaultFixup:
1072 case ThreadEventPair_Reusable:
1073 case ThreadQuerySetWin32StartAddress:
1074 case ThreadZeroTlsCell:
1075 case ThreadPerformanceCount:
1076 case ThreadIdealProcessor:
1077 case ThreadPriorityBoost:
1078 case ThreadSetTlsArrayAddress:
1079 case ThreadIsIoPending:
1081 FIXME( "info class %d not supported yet\n", class );
1082 return STATUS_NOT_IMPLEMENTED;
1087 /******************************************************************************
1088 * NtSetInformationThread (NTDLL.@)
1089 * ZwSetInformationThread (NTDLL.@)
1091 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1092 LPCVOID data, ULONG length )
1097 case ThreadZeroTlsCell:
1098 if (handle == GetCurrentThread())
1103 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1104 index = *(const DWORD *)data;
1105 if (index < TLS_MINIMUM_AVAILABLE)
1107 RtlAcquirePebLock();
1108 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1110 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1111 teb->TlsSlots[index] = 0;
1113 RtlReleasePebLock();
1117 index -= TLS_MINIMUM_AVAILABLE;
1118 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1119 return STATUS_INVALID_PARAMETER;
1120 RtlAcquirePebLock();
1121 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1123 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1124 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1126 RtlReleasePebLock();
1128 return STATUS_SUCCESS;
1130 FIXME( "ZeroTlsCell not supported on other threads\n" );
1131 return STATUS_NOT_IMPLEMENTED;
1133 case ThreadImpersonationToken:
1135 const HANDLE *phToken = data;
1136 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1137 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1138 SERVER_START_REQ( set_thread_info )
1140 req->handle = wine_server_obj_handle( handle );
1141 req->token = wine_server_obj_handle( *phToken );
1142 req->mask = SET_THREAD_INFO_TOKEN;
1143 status = wine_server_call( req );
1148 case ThreadBasePriority:
1150 const DWORD *pprio = data;
1151 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1152 SERVER_START_REQ( set_thread_info )
1154 req->handle = wine_server_obj_handle( handle );
1155 req->priority = *pprio;
1156 req->mask = SET_THREAD_INFO_PRIORITY;
1157 status = wine_server_call( req );
1162 case ThreadAffinityMask:
1164 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1165 const ULONG_PTR *paff = data;
1166 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1167 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1168 if (!*paff) return STATUS_INVALID_PARAMETER;
1169 SERVER_START_REQ( set_thread_info )
1171 req->handle = wine_server_obj_handle( handle );
1172 req->affinity = *paff;
1173 req->mask = SET_THREAD_INFO_AFFINITY;
1174 status = wine_server_call( req );
1179 case ThreadHideFromDebugger:
1180 /* pretend the call succeeded to satisfy some code protectors */
1181 return STATUS_SUCCESS;
1183 case ThreadBasicInformation:
1185 case ThreadPriority:
1186 case ThreadDescriptorTableEntry:
1187 case ThreadEnableAlignmentFaultFixup:
1188 case ThreadEventPair_Reusable:
1189 case ThreadQuerySetWin32StartAddress:
1190 case ThreadPerformanceCount:
1191 case ThreadAmILastThread:
1192 case ThreadIdealProcessor:
1193 case ThreadPriorityBoost:
1194 case ThreadSetTlsArrayAddress:
1195 case ThreadIsIoPending:
1197 FIXME( "info class %d not supported yet\n", class );
1198 return STATUS_NOT_IMPLEMENTED;