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;
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 int nb_threads = 1;
70 /***********************************************************************
73 * Copy a unicode string from the startup info.
75 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
79 str->MaximumLength = len + sizeof(WCHAR);
80 memcpy( str->Buffer, *src, len );
81 str->Buffer[len / sizeof(WCHAR)] = 0;
82 *src += len / sizeof(WCHAR);
83 *dst += len / sizeof(WCHAR) + 1;
86 /***********************************************************************
87 * init_user_process_params
89 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
91 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
95 SIZE_T info_size, env_size, size, alloc_size;
98 RTL_USER_PROCESS_PARAMETERS *params = NULL;
100 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
101 return STATUS_NO_MEMORY;
103 SERVER_START_REQ( get_startup_info )
105 wine_server_set_reply( req, info, data_size );
106 if (!(status = wine_server_call( req )))
108 data_size = wine_server_reply_size( reply );
109 info_size = reply->info_size;
110 env_size = data_size - info_size;
111 *exe_file = wine_server_ptr_handle( reply->exe_file );
115 if (status != STATUS_SUCCESS) goto done;
117 size = sizeof(*params);
118 size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
119 size += info->dllpath_len + sizeof(WCHAR);
120 size += info->imagepath_len + sizeof(WCHAR);
121 size += info->cmdline_len + sizeof(WCHAR);
122 size += info->title_len + sizeof(WCHAR);
123 size += info->desktop_len + sizeof(WCHAR);
124 size += info->shellinfo_len + sizeof(WCHAR);
125 size += info->runtime_len + sizeof(WCHAR);
128 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &alloc_size,
129 MEM_COMMIT, PAGE_READWRITE );
130 if (status != STATUS_SUCCESS) goto done;
132 NtCurrentTeb()->Peb->ProcessParameters = params;
133 params->AllocationSize = alloc_size;
135 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
136 params->DebugFlags = info->debug_flags;
137 params->ConsoleHandle = wine_server_ptr_handle( info->console );
138 params->ConsoleFlags = info->console_flags;
139 params->hStdInput = wine_server_ptr_handle( info->hstdin );
140 params->hStdOutput = wine_server_ptr_handle( info->hstdout );
141 params->hStdError = wine_server_ptr_handle( info->hstderr );
142 params->dwX = info->x;
143 params->dwY = info->y;
144 params->dwXSize = info->xsize;
145 params->dwYSize = info->ysize;
146 params->dwXCountChars = info->xchars;
147 params->dwYCountChars = info->ychars;
148 params->dwFillAttribute = info->attribute;
149 params->dwFlags = info->flags;
150 params->wShowWindow = info->show;
152 src = (WCHAR *)(info + 1);
153 dst = (WCHAR *)(params + 1);
155 /* current directory needs more space */
156 get_unicode_string( ¶ms->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
157 params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
158 dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
160 get_unicode_string( ¶ms->DllPath, &src, &dst, info->dllpath_len );
161 get_unicode_string( ¶ms->ImagePathName, &src, &dst, info->imagepath_len );
162 get_unicode_string( ¶ms->CommandLine, &src, &dst, info->cmdline_len );
163 get_unicode_string( ¶ms->WindowTitle, &src, &dst, info->title_len );
164 get_unicode_string( ¶ms->Desktop, &src, &dst, info->desktop_len );
165 get_unicode_string( ¶ms->ShellInfo, &src, &dst, info->shellinfo_len );
167 /* runtime info isn't a real string */
168 params->RuntimeInfo.Buffer = dst;
169 params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
170 memcpy( dst, src, info->runtime_len );
172 /* environment needs to be a separate memory block */
174 alloc_size = max( 1, env_size );
175 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
176 MEM_COMMIT, PAGE_READWRITE );
177 if (status != STATUS_SUCCESS) goto done;
178 memcpy( ptr, (char *)info + info_size, env_size );
179 params->Environment = ptr;
182 RtlFreeHeap( GetProcessHeap(), 0, info );
186 /***********************************************************************
189 * Setup the initial thread.
191 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
193 HANDLE thread_init(void)
197 SIZE_T size, info_size;
200 struct ntdll_thread_data *thread_data;
201 static struct debug_info debug_info; /* debug info for initial thread */
205 /* reserve space for shared user data */
207 addr = (void *)0x7ffe0000;
209 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
210 user_shared_data = addr;
212 /* allocate and initialize the PEB */
216 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
217 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
220 peb->ProcessParameters = ¶ms;
221 peb->TlsBitmap = &tls_bitmap;
222 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
223 peb->FlsBitmap = &fls_bitmap;
225 params.CurrentDirectory.DosPath.Buffer = current_dir;
226 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
227 params.wShowWindow = 1; /* SW_SHOWNORMAL */
228 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
229 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
230 sizeof(peb->TlsExpansionBitmapBits) * 8 );
231 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
232 InitializeListHead( &peb->FlsListHead );
233 InitializeListHead( &ldr.InLoadOrderModuleList );
234 InitializeListHead( &ldr.InMemoryOrderModuleList );
235 InitializeListHead( &ldr.InInitializationOrderModuleList );
236 InitializeListHead( &tls_links );
238 /* allocate and initialize the initial TEB */
240 signal_alloc_thread( &teb );
242 teb->Tib.StackBase = (void *)~0UL;
243 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
244 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
246 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
247 thread_data->request_fd = -1;
248 thread_data->reply_fd = -1;
249 thread_data->wait_fd[0] = -1;
250 thread_data->wait_fd[1] = -1;
251 thread_data->debug_info = &debug_info;
252 InsertHeadList( &tls_links, &teb->TlsLinks );
254 signal_init_thread( teb );
255 virtual_init_threading();
257 debug_info.str_pos = debug_info.strings;
258 debug_info.out_pos = debug_info.output;
261 /* setup the server connection */
262 server_init_process();
263 info_size = server_init_thread( peb );
265 /* create the process heap */
266 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
268 MESSAGE( "wine: failed to create the process heap\n" );
272 /* allocate user parameters */
275 init_user_process_params( info_size, &exe_file );
279 if (isatty(0) || isatty(1) || isatty(2))
280 params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
282 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
284 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
286 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
289 /* initialize time values in user_shared_data */
290 NtQuerySystemTime( &now );
291 user_shared_data->SystemTime.LowPart = now.u.LowPart;
292 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
293 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
294 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
295 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
296 user_shared_data->TickCountMultiplier = 1 << 24;
304 /***********************************************************************
307 void terminate_thread( int status )
309 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
310 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
312 close( ntdll_get_thread_data()->wait_fd[0] );
313 close( ntdll_get_thread_data()->wait_fd[1] );
314 close( ntdll_get_thread_data()->reply_fd );
315 close( ntdll_get_thread_data()->request_fd );
316 pthread_exit( UIntToPtr(status) );
320 /***********************************************************************
323 void exit_thread( int status )
325 static void *prev_teb;
328 if (status) /* send the exit code to the server (0 is already the default) */
330 SERVER_START_REQ( terminate_thread )
332 req->handle = wine_server_obj_handle( GetCurrentThread() );
333 req->exit_code = status;
334 wine_server_call( req );
339 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
341 LdrShutdownProcess();
347 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
349 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
350 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
352 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
354 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
356 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
358 pthread_join( thread_data->pthread_id, NULL );
359 signal_free_thread( teb );
362 close( ntdll_get_thread_data()->wait_fd[0] );
363 close( ntdll_get_thread_data()->wait_fd[1] );
364 close( ntdll_get_thread_data()->reply_fd );
365 close( ntdll_get_thread_data()->request_fd );
366 pthread_exit( UIntToPtr(status) );
370 /***********************************************************************
373 * Startup routine for a newly created thread.
375 static void start_thread( struct startup_info *info )
377 TEB *teb = info->teb;
378 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
379 PRTL_THREAD_START_ROUTINE func = info->entry_point;
380 void *arg = info->entry_arg;
381 struct debug_info debug_info;
383 debug_info.str_pos = debug_info.strings;
384 debug_info.out_pos = debug_info.output;
385 thread_data->debug_info = &debug_info;
386 thread_data->pthread_id = pthread_self();
388 signal_init_thread( teb );
389 server_init_thread( func );
390 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
393 InsertHeadList( &tls_links, &teb->TlsLinks );
396 MODULE_DllThreadAttach( NULL );
399 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
401 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
405 /***********************************************************************
406 * RtlCreateUserThread (NTDLL.@)
408 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
409 BOOLEAN suspended, PVOID stack_addr,
410 SIZE_T stack_reserve, SIZE_T stack_commit,
411 PRTL_THREAD_START_ROUTINE start, void *param,
412 HANDLE *handle_ptr, CLIENT_ID *id )
415 pthread_t pthread_id;
417 struct ntdll_thread_data *thread_data;
418 struct startup_info *info = NULL;
425 if (process != NtCurrentProcess())
430 memset( &call, 0, sizeof(call) );
432 call.create_thread.type = APC_CREATE_THREAD;
433 call.create_thread.func = wine_server_client_ptr( start );
434 call.create_thread.arg = wine_server_client_ptr( param );
435 call.create_thread.reserve = stack_reserve;
436 call.create_thread.commit = stack_commit;
437 call.create_thread.suspend = suspended;
438 status = NTDLL_queue_process_apc( process, &call, &result );
439 if (status != STATUS_SUCCESS) return status;
441 if (result.create_thread.status == STATUS_SUCCESS)
443 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
444 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
445 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
447 return result.create_thread.status;
450 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
451 wine_server_send_fd( request_pipe[0] );
453 SERVER_START_REQ( new_thread )
455 req->access = THREAD_ALL_ACCESS;
456 req->attributes = 0; /* FIXME */
457 req->suspend = suspended;
458 req->request_fd = request_pipe[0];
459 if (!(status = wine_server_call( req )))
461 handle = wine_server_ptr_handle( reply->handle );
464 close( request_pipe[0] );
470 close( request_pipe[1] );
474 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
476 if ((status = signal_alloc_thread( &teb ))) goto error;
478 teb->Peb = NtCurrentTeb()->Peb;
479 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
480 teb->ClientId.UniqueThread = ULongToHandle(tid);
481 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
482 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
484 info = (struct startup_info *)(teb + 1);
486 info->entry_point = start;
487 info->entry_arg = param;
489 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
490 thread_data->request_fd = request_pipe[1];
491 thread_data->reply_fd = -1;
492 thread_data->wait_fd[0] = -1;
493 thread_data->wait_fd[1] = -1;
495 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
497 pthread_attr_init( &attr );
498 pthread_attr_setstack( &attr, teb->DeallocationStack,
499 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
500 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
501 interlocked_xchg_add( &nb_threads, 1 );
502 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
504 interlocked_xchg_add( &nb_threads, -1 );
505 pthread_attr_destroy( &attr );
506 status = STATUS_NO_MEMORY;
509 pthread_attr_destroy( &attr );
510 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
512 if (id) id->UniqueThread = ULongToHandle(tid);
513 if (handle_ptr) *handle_ptr = handle;
514 else NtClose( handle );
516 return STATUS_SUCCESS;
519 if (teb) signal_free_thread( teb );
520 if (handle) NtClose( handle );
521 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
522 close( request_pipe[1] );
527 /******************************************************************************
528 * RtlGetNtGlobalFlags (NTDLL.@)
530 ULONG WINAPI RtlGetNtGlobalFlags(void)
532 if (!peb) return 0; /* init not done yet */
533 return peb->NtGlobalFlag;
537 /***********************************************************************
538 * NtOpenThread (NTDLL.@)
539 * ZwOpenThread (NTDLL.@)
541 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
542 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
546 SERVER_START_REQ( open_thread )
548 req->tid = HandleToULong(id->UniqueThread);
549 req->access = access;
550 req->attributes = attr ? attr->Attributes : 0;
551 ret = wine_server_call( req );
552 *handle = wine_server_ptr_handle( reply->handle );
559 /******************************************************************************
560 * NtSuspendThread (NTDLL.@)
561 * ZwSuspendThread (NTDLL.@)
563 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
567 SERVER_START_REQ( suspend_thread )
569 req->handle = wine_server_obj_handle( handle );
570 if (!(ret = wine_server_call( req ))) *count = reply->count;
577 /******************************************************************************
578 * NtResumeThread (NTDLL.@)
579 * ZwResumeThread (NTDLL.@)
581 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
585 SERVER_START_REQ( resume_thread )
587 req->handle = wine_server_obj_handle( handle );
588 if (!(ret = wine_server_call( req ))) *count = reply->count;
595 /******************************************************************************
596 * NtAlertResumeThread (NTDLL.@)
597 * ZwAlertResumeThread (NTDLL.@)
599 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
601 FIXME( "stub: should alert thread %p\n", handle );
602 return NtResumeThread( handle, count );
606 /******************************************************************************
607 * NtAlertThread (NTDLL.@)
608 * ZwAlertThread (NTDLL.@)
610 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
612 FIXME( "stub: %p\n", handle );
613 return STATUS_NOT_IMPLEMENTED;
617 /******************************************************************************
618 * NtTerminateThread (NTDLL.@)
619 * ZwTerminateThread (NTDLL.@)
621 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
626 SERVER_START_REQ( terminate_thread )
628 req->handle = wine_server_obj_handle( handle );
629 req->exit_code = exit_code;
630 ret = wine_server_call( req );
631 self = !ret && reply->self;
635 if (self) abort_thread( exit_code );
640 /******************************************************************************
641 * NtQueueApcThread (NTDLL.@)
643 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
644 ULONG_PTR arg2, ULONG_PTR arg3 )
647 SERVER_START_REQ( queue_apc )
649 req->handle = wine_server_obj_handle( handle );
652 req->call.type = APC_USER;
653 req->call.user.func = wine_server_client_ptr( func );
654 req->call.user.args[0] = arg1;
655 req->call.user.args[1] = arg2;
656 req->call.user.args[2] = arg3;
658 else req->call.type = APC_NONE; /* wake up only */
659 ret = wine_server_call( req );
666 /***********************************************************************
667 * NtSetContextThread (NTDLL.@)
668 * ZwSetContextThread (NTDLL.@)
670 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
677 /* on i386 debug registers always require a server call */
678 self = (handle == GetCurrentThread());
679 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
681 self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
682 ntdll_get_thread_data()->dr1 == context->Dr1 &&
683 ntdll_get_thread_data()->dr2 == context->Dr2 &&
684 ntdll_get_thread_data()->dr3 == context->Dr3 &&
685 ntdll_get_thread_data()->dr6 == context->Dr6 &&
686 ntdll_get_thread_data()->dr7 == context->Dr7);
692 context_t server_context;
694 context_to_server( &server_context, context );
696 SERVER_START_REQ( set_thread_context )
698 req->handle = wine_server_obj_handle( handle );
700 wine_server_add_data( req, &server_context, sizeof(server_context) );
701 ret = wine_server_call( req );
706 if (ret == STATUS_PENDING)
708 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
710 for (i = 0; i < 100; i++)
712 SERVER_START_REQ( set_thread_context )
714 req->handle = wine_server_obj_handle( handle );
716 wine_server_add_data( req, &server_context, sizeof(server_context) );
717 ret = wine_server_call( req );
720 if (ret == STATUS_PENDING)
722 LARGE_INTEGER timeout;
723 timeout.QuadPart = -10000;
724 NtDelayExecution( FALSE, &timeout );
728 NtResumeThread( handle, &dummy );
730 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
736 if (self) set_cpu_context( context );
737 return STATUS_SUCCESS;
741 /* convert CPU-specific flags to generic server flags */
742 static inline unsigned int get_server_context_flags( DWORD flags )
744 unsigned int ret = 0;
746 flags &= 0x3f; /* mask CPU id flags */
747 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
748 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
749 #ifdef CONTEXT_SEGMENTS
750 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
752 #ifdef CONTEXT_FLOATING_POINT
753 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
755 #ifdef CONTEXT_DEBUG_REGISTERS
756 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
758 #ifdef CONTEXT_EXTENDED_REGISTERS
759 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
764 /***********************************************************************
765 * NtGetContextThread (NTDLL.@)
766 * ZwGetContextThread (NTDLL.@)
768 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
772 DWORD needed_flags = context->ContextFlags;
773 BOOL self = (handle == GetCurrentThread());
776 /* on i386 debug registers always require a server call */
777 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
782 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
783 context_t server_context;
785 SERVER_START_REQ( get_thread_context )
787 req->handle = wine_server_obj_handle( handle );
788 req->flags = server_flags;
790 wine_server_set_reply( req, &server_context, sizeof(server_context) );
791 ret = wine_server_call( req );
796 if (ret == STATUS_PENDING)
798 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
800 for (i = 0; i < 100; i++)
802 SERVER_START_REQ( get_thread_context )
804 req->handle = wine_server_obj_handle( handle );
805 req->flags = server_flags;
807 wine_server_set_reply( req, &server_context, sizeof(server_context) );
808 ret = wine_server_call( req );
811 if (ret == STATUS_PENDING)
813 LARGE_INTEGER timeout;
814 timeout.QuadPart = -10000;
815 NtDelayExecution( FALSE, &timeout );
819 NtResumeThread( handle, &dummy );
821 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
823 if (!ret) ret = context_from_server( context, &server_context );
825 needed_flags &= ~context->ContextFlags;
833 RtlCaptureContext( &ctx );
834 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
835 context->ContextFlags |= ctx.ContextFlags & needed_flags;
838 /* update the cached version of the debug registers */
839 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
841 ntdll_get_thread_data()->dr0 = context->Dr0;
842 ntdll_get_thread_data()->dr1 = context->Dr1;
843 ntdll_get_thread_data()->dr2 = context->Dr2;
844 ntdll_get_thread_data()->dr3 = context->Dr3;
845 ntdll_get_thread_data()->dr6 = context->Dr6;
846 ntdll_get_thread_data()->dr7 = context->Dr7;
850 return STATUS_SUCCESS;
854 /******************************************************************************
855 * NtQueryInformationThread (NTDLL.@)
856 * ZwQueryInformationThread (NTDLL.@)
858 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
859 void *data, ULONG length, ULONG *ret_len )
865 case ThreadBasicInformation:
867 THREAD_BASIC_INFORMATION info;
868 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
870 SERVER_START_REQ( get_thread_info )
872 req->handle = wine_server_obj_handle( handle );
874 if (!(status = wine_server_call( req )))
876 info.ExitStatus = reply->exit_code;
877 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
878 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
879 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
880 info.AffinityMask = reply->affinity & affinity_mask;
881 info.Priority = reply->priority;
882 info.BasePriority = reply->priority; /* FIXME */
886 if (status == STATUS_SUCCESS)
888 if (data) memcpy( data, &info, min( length, sizeof(info) ));
889 if (ret_len) *ret_len = min( length, sizeof(info) );
893 case ThreadAffinityMask:
895 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
896 ULONG_PTR affinity = 0;
898 SERVER_START_REQ( get_thread_info )
900 req->handle = wine_server_obj_handle( handle );
902 if (!(status = wine_server_call( req )))
903 affinity = reply->affinity & affinity_mask;
906 if (status == STATUS_SUCCESS)
908 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
909 if (ret_len) *ret_len = min( length, sizeof(affinity) );
915 KERNEL_USER_TIMES kusrt;
916 /* We need to do a server call to get the creation time or exit time */
917 /* This works on any thread */
918 SERVER_START_REQ( get_thread_info )
920 req->handle = wine_server_obj_handle( handle );
922 status = wine_server_call( req );
923 if (status == STATUS_SUCCESS)
925 kusrt.CreateTime.QuadPart = reply->creation_time;
926 kusrt.ExitTime.QuadPart = reply->exit_time;
930 if (status == STATUS_SUCCESS)
932 /* We call times(2) for kernel time or user time */
933 /* We can only (portably) do this for the current thread */
934 if (handle == GetCurrentThread())
937 long clocks_per_sec = sysconf(_SC_CLK_TCK);
940 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
941 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
945 static BOOL reported = FALSE;
947 kusrt.KernelTime.QuadPart = 0;
948 kusrt.UserTime.QuadPart = 0;
950 TRACE("Cannot get kerneltime or usertime of other threads\n");
953 FIXME("Cannot get kerneltime or usertime of other threads\n");
957 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
958 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
962 case ThreadDescriptorTableEntry:
965 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
966 if (length < sizeof(*tdi))
967 status = STATUS_INFO_LENGTH_MISMATCH;
968 else if (!(tdi->Selector & 4)) /* GDT selector */
970 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
971 status = STATUS_SUCCESS;
972 if (!sel) /* null selector */
973 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
976 tdi->Entry.BaseLow = 0;
977 tdi->Entry.HighWord.Bits.BaseMid = 0;
978 tdi->Entry.HighWord.Bits.BaseHi = 0;
979 tdi->Entry.LimitLow = 0xffff;
980 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
981 tdi->Entry.HighWord.Bits.Dpl = 3;
982 tdi->Entry.HighWord.Bits.Sys = 0;
983 tdi->Entry.HighWord.Bits.Pres = 1;
984 tdi->Entry.HighWord.Bits.Granularity = 1;
985 tdi->Entry.HighWord.Bits.Default_Big = 1;
986 tdi->Entry.HighWord.Bits.Type = 0x12;
987 /* it has to be one of the system GDT selectors */
988 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
990 if (sel == (wine_get_cs() & ~3))
991 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
992 else status = STATUS_ACCESS_DENIED;
998 SERVER_START_REQ( get_selector_entry )
1000 req->handle = wine_server_obj_handle( handle );
1001 req->entry = tdi->Selector >> 3;
1002 status = wine_server_call( req );
1005 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1006 status = STATUS_ACCESS_VIOLATION;
1009 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1010 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1011 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1017 if (status == STATUS_SUCCESS && ret_len)
1018 /* yes, that's a bit strange, but it's the way it is */
1019 *ret_len = sizeof(LDT_ENTRY);
1021 status = STATUS_NOT_IMPLEMENTED;
1025 case ThreadAmILastThread:
1027 SERVER_START_REQ(get_thread_info)
1029 req->handle = wine_server_obj_handle( handle );
1031 status = wine_server_call( req );
1032 if (status == STATUS_SUCCESS)
1034 BOOLEAN last = reply->last;
1035 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1036 if (ret_len) *ret_len = min( length, sizeof(last) );
1042 case ThreadPriority:
1043 case ThreadBasePriority:
1044 case ThreadImpersonationToken:
1045 case ThreadEnableAlignmentFaultFixup:
1046 case ThreadEventPair_Reusable:
1047 case ThreadQuerySetWin32StartAddress:
1048 case ThreadZeroTlsCell:
1049 case ThreadPerformanceCount:
1050 case ThreadIdealProcessor:
1051 case ThreadPriorityBoost:
1052 case ThreadSetTlsArrayAddress:
1053 case ThreadIsIoPending:
1055 FIXME( "info class %d not supported yet\n", class );
1056 return STATUS_NOT_IMPLEMENTED;
1061 /******************************************************************************
1062 * NtSetInformationThread (NTDLL.@)
1063 * ZwSetInformationThread (NTDLL.@)
1065 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1066 LPCVOID data, ULONG length )
1071 case ThreadZeroTlsCell:
1072 if (handle == GetCurrentThread())
1077 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1078 index = *(const DWORD *)data;
1079 if (index < TLS_MINIMUM_AVAILABLE)
1081 RtlAcquirePebLock();
1082 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1084 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1085 teb->TlsSlots[index] = 0;
1087 RtlReleasePebLock();
1091 index -= TLS_MINIMUM_AVAILABLE;
1092 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1093 return STATUS_INVALID_PARAMETER;
1094 RtlAcquirePebLock();
1095 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1097 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1098 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1100 RtlReleasePebLock();
1102 return STATUS_SUCCESS;
1104 FIXME( "ZeroTlsCell not supported on other threads\n" );
1105 return STATUS_NOT_IMPLEMENTED;
1107 case ThreadImpersonationToken:
1109 const HANDLE *phToken = data;
1110 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1111 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1112 SERVER_START_REQ( set_thread_info )
1114 req->handle = wine_server_obj_handle( handle );
1115 req->token = wine_server_obj_handle( *phToken );
1116 req->mask = SET_THREAD_INFO_TOKEN;
1117 status = wine_server_call( req );
1122 case ThreadBasePriority:
1124 const DWORD *pprio = data;
1125 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1126 SERVER_START_REQ( set_thread_info )
1128 req->handle = wine_server_obj_handle( handle );
1129 req->priority = *pprio;
1130 req->mask = SET_THREAD_INFO_PRIORITY;
1131 status = wine_server_call( req );
1136 case ThreadAffinityMask:
1138 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1141 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1142 req_aff = *(const ULONG_PTR *)data;
1143 if ((ULONG)req_aff == ~0u) req_aff = affinity_mask;
1144 else if (req_aff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1145 else if (!req_aff) return STATUS_INVALID_PARAMETER;
1146 SERVER_START_REQ( set_thread_info )
1148 req->handle = wine_server_obj_handle( handle );
1149 req->affinity = req_aff;
1150 req->mask = SET_THREAD_INFO_AFFINITY;
1151 status = wine_server_call( req );
1156 case ThreadHideFromDebugger:
1157 /* pretend the call succeeded to satisfy some code protectors */
1158 return STATUS_SUCCESS;
1160 case ThreadBasicInformation:
1162 case ThreadPriority:
1163 case ThreadDescriptorTableEntry:
1164 case ThreadEnableAlignmentFaultFixup:
1165 case ThreadEventPair_Reusable:
1166 case ThreadQuerySetWin32StartAddress:
1167 case ThreadPerformanceCount:
1168 case ThreadAmILastThread:
1169 case ThreadIdealProcessor:
1170 case ThreadPriorityBoost:
1171 case ThreadSetTlsArrayAddress:
1172 case ThreadIsIoPending:
1174 FIXME( "info class %d not supported yet\n", class );
1175 return STATUS_NOT_IMPLEMENTED;