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>
33 #ifdef HAVE_SYS_SYSCALL_H
34 #include <sys/syscall.h>
37 #define NONAMELESSUNION
39 #define WIN32_NO_STATUS
41 #include "wine/library.h"
42 #include "wine/server.h"
43 #include "wine/debug.h"
44 #include "ntdll_misc.h"
46 #include "wine/exception.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(thread);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
53 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
55 /* info passed to a starting thread */
59 PRTL_THREAD_START_ROUTINE entry_point;
64 static PEB_LDR_DATA ldr;
65 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
66 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
67 static RTL_BITMAP tls_bitmap;
68 static RTL_BITMAP tls_expansion_bitmap;
69 static RTL_BITMAP fls_bitmap;
70 static LIST_ENTRY tls_links;
71 static int nb_threads = 1;
73 /***********************************************************************
76 * Copy a unicode string from the startup info.
78 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
82 str->MaximumLength = len + sizeof(WCHAR);
83 memcpy( str->Buffer, *src, len );
84 str->Buffer[len / sizeof(WCHAR)] = 0;
85 *src += len / sizeof(WCHAR);
86 *dst += len / sizeof(WCHAR) + 1;
89 /***********************************************************************
90 * init_user_process_params
92 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
94 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
98 SIZE_T info_size, env_size, size, alloc_size;
100 startup_info_t *info;
101 RTL_USER_PROCESS_PARAMETERS *params = NULL;
103 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
104 return STATUS_NO_MEMORY;
106 SERVER_START_REQ( get_startup_info )
108 wine_server_set_reply( req, info, data_size );
109 if (!(status = wine_server_call( req )))
111 data_size = wine_server_reply_size( reply );
112 info_size = reply->info_size;
113 env_size = data_size - info_size;
114 *exe_file = wine_server_ptr_handle( reply->exe_file );
118 if (status != STATUS_SUCCESS) goto done;
120 size = sizeof(*params);
121 size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
122 size += info->dllpath_len + sizeof(WCHAR);
123 size += info->imagepath_len + sizeof(WCHAR);
124 size += info->cmdline_len + sizeof(WCHAR);
125 size += info->title_len + sizeof(WCHAR);
126 size += info->desktop_len + sizeof(WCHAR);
127 size += info->shellinfo_len + sizeof(WCHAR);
128 size += info->runtime_len + sizeof(WCHAR);
131 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &alloc_size,
132 MEM_COMMIT, PAGE_READWRITE );
133 if (status != STATUS_SUCCESS) goto done;
135 NtCurrentTeb()->Peb->ProcessParameters = params;
136 params->AllocationSize = alloc_size;
138 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
139 params->DebugFlags = info->debug_flags;
140 params->ConsoleHandle = wine_server_ptr_handle( info->console );
141 params->ConsoleFlags = info->console_flags;
142 params->hStdInput = wine_server_ptr_handle( info->hstdin );
143 params->hStdOutput = wine_server_ptr_handle( info->hstdout );
144 params->hStdError = wine_server_ptr_handle( info->hstderr );
145 params->dwX = info->x;
146 params->dwY = info->y;
147 params->dwXSize = info->xsize;
148 params->dwYSize = info->ysize;
149 params->dwXCountChars = info->xchars;
150 params->dwYCountChars = info->ychars;
151 params->dwFillAttribute = info->attribute;
152 params->dwFlags = info->flags;
153 params->wShowWindow = info->show;
155 src = (WCHAR *)(info + 1);
156 dst = (WCHAR *)(params + 1);
158 /* current directory needs more space */
159 get_unicode_string( ¶ms->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
160 params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
161 dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
163 get_unicode_string( ¶ms->DllPath, &src, &dst, info->dllpath_len );
164 get_unicode_string( ¶ms->ImagePathName, &src, &dst, info->imagepath_len );
165 get_unicode_string( ¶ms->CommandLine, &src, &dst, info->cmdline_len );
166 get_unicode_string( ¶ms->WindowTitle, &src, &dst, info->title_len );
167 get_unicode_string( ¶ms->Desktop, &src, &dst, info->desktop_len );
168 get_unicode_string( ¶ms->ShellInfo, &src, &dst, info->shellinfo_len );
170 /* runtime info isn't a real string */
171 params->RuntimeInfo.Buffer = dst;
172 params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
173 memcpy( dst, src, info->runtime_len );
175 /* environment needs to be a separate memory block */
177 alloc_size = max( 1, env_size );
178 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
179 MEM_COMMIT, PAGE_READWRITE );
180 if (status != STATUS_SUCCESS) goto done;
181 memcpy( ptr, (char *)info + info_size, env_size );
182 params->Environment = ptr;
185 RtlFreeHeap( GetProcessHeap(), 0, info );
189 /***********************************************************************
192 * Setup the initial thread.
194 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
196 HANDLE thread_init(void)
200 SIZE_T size, info_size;
204 struct ntdll_thread_data *thread_data;
205 static struct debug_info debug_info; /* debug info for initial thread */
209 /* reserve space for shared user data */
211 addr = (void *)0x7ffe0000;
213 status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
214 MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
217 MESSAGE( "wine: failed to map the shared user data: %08x\n", status );
220 user_shared_data = addr;
222 /* allocate and initialize the PEB */
226 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
227 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
230 peb->ProcessParameters = ¶ms;
231 peb->TlsBitmap = &tls_bitmap;
232 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
233 peb->FlsBitmap = &fls_bitmap;
235 params.CurrentDirectory.DosPath.Buffer = current_dir;
236 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
237 params.wShowWindow = 1; /* SW_SHOWNORMAL */
238 ldr.Length = sizeof(ldr);
239 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
240 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
241 sizeof(peb->TlsExpansionBitmapBits) * 8 );
242 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
243 InitializeListHead( &peb->FlsListHead );
244 InitializeListHead( &ldr.InLoadOrderModuleList );
245 InitializeListHead( &ldr.InMemoryOrderModuleList );
246 InitializeListHead( &ldr.InInitializationOrderModuleList );
247 InitializeListHead( &tls_links );
249 /* allocate and initialize the initial TEB */
251 signal_alloc_thread( &teb );
253 teb->Tib.StackBase = (void *)~0UL;
254 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
255 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
257 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
258 thread_data->request_fd = -1;
259 thread_data->reply_fd = -1;
260 thread_data->wait_fd[0] = -1;
261 thread_data->wait_fd[1] = -1;
262 thread_data->debug_info = &debug_info;
263 InsertHeadList( &tls_links, &teb->TlsLinks );
265 signal_init_thread( teb );
266 virtual_init_threading();
268 debug_info.str_pos = debug_info.strings;
269 debug_info.out_pos = debug_info.output;
272 /* setup the server connection */
273 server_init_process();
274 info_size = server_init_thread( peb );
276 /* create the process heap */
277 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
279 MESSAGE( "wine: failed to create the process heap\n" );
283 /* allocate user parameters */
286 init_user_process_params( info_size, &exe_file );
290 if (isatty(0) || isatty(1) || isatty(2))
291 params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
293 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
295 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
297 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
300 /* initialize time values in user_shared_data */
301 NtQuerySystemTime( &now );
302 user_shared_data->SystemTime.LowPart = now.u.LowPart;
303 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
304 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
305 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
306 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
307 user_shared_data->TickCountMultiplier = 1 << 24;
315 /***********************************************************************
318 void terminate_thread( int status )
320 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
321 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
323 close( ntdll_get_thread_data()->wait_fd[0] );
324 close( ntdll_get_thread_data()->wait_fd[1] );
325 close( ntdll_get_thread_data()->reply_fd );
326 close( ntdll_get_thread_data()->request_fd );
327 pthread_exit( UIntToPtr(status) );
331 /***********************************************************************
334 void exit_thread( int status )
336 static void *prev_teb;
339 if (status) /* send the exit code to the server (0 is already the default) */
341 SERVER_START_REQ( terminate_thread )
343 req->handle = wine_server_obj_handle( GetCurrentThread() );
344 req->exit_code = status;
345 wine_server_call( req );
350 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
352 LdrShutdownProcess();
358 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
360 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
361 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
363 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
365 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
367 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
369 if (thread_data->pthread_id)
371 pthread_join( thread_data->pthread_id, NULL );
372 signal_free_thread( teb );
376 close( ntdll_get_thread_data()->wait_fd[0] );
377 close( ntdll_get_thread_data()->wait_fd[1] );
378 close( ntdll_get_thread_data()->reply_fd );
379 close( ntdll_get_thread_data()->request_fd );
380 pthread_exit( UIntToPtr(status) );
384 /***********************************************************************
387 * Startup routine for a newly created thread.
389 static void start_thread( struct startup_info *info )
391 TEB *teb = info->teb;
392 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
393 PRTL_THREAD_START_ROUTINE func = info->entry_point;
394 void *arg = info->entry_arg;
395 struct debug_info debug_info;
397 debug_info.str_pos = debug_info.strings;
398 debug_info.out_pos = debug_info.output;
399 thread_data->debug_info = &debug_info;
400 thread_data->pthread_id = pthread_self();
402 signal_init_thread( teb );
403 server_init_thread( func );
404 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
407 InsertHeadList( &tls_links, &teb->TlsLinks );
410 MODULE_DllThreadAttach( NULL );
413 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
415 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
419 /***********************************************************************
420 * RtlCreateUserThread (NTDLL.@)
422 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
423 BOOLEAN suspended, PVOID stack_addr,
424 SIZE_T stack_reserve, SIZE_T stack_commit,
425 PRTL_THREAD_START_ROUTINE start, void *param,
426 HANDLE *handle_ptr, CLIENT_ID *id )
429 pthread_t pthread_id;
431 struct ntdll_thread_data *thread_data;
432 struct startup_info *info = NULL;
439 if (process != NtCurrentProcess())
444 memset( &call, 0, sizeof(call) );
446 call.create_thread.type = APC_CREATE_THREAD;
447 call.create_thread.func = wine_server_client_ptr( start );
448 call.create_thread.arg = wine_server_client_ptr( param );
449 call.create_thread.reserve = stack_reserve;
450 call.create_thread.commit = stack_commit;
451 call.create_thread.suspend = suspended;
452 status = NTDLL_queue_process_apc( process, &call, &result );
453 if (status != STATUS_SUCCESS) return status;
455 if (result.create_thread.status == STATUS_SUCCESS)
457 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
458 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
459 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
461 return result.create_thread.status;
464 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
465 wine_server_send_fd( request_pipe[0] );
467 SERVER_START_REQ( new_thread )
469 req->access = THREAD_ALL_ACCESS;
470 req->attributes = 0; /* FIXME */
471 req->suspend = suspended;
472 req->request_fd = request_pipe[0];
473 if (!(status = wine_server_call( req )))
475 handle = wine_server_ptr_handle( reply->handle );
478 close( request_pipe[0] );
484 close( request_pipe[1] );
488 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
490 if ((status = signal_alloc_thread( &teb ))) goto error;
492 teb->Peb = NtCurrentTeb()->Peb;
493 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
494 teb->ClientId.UniqueThread = ULongToHandle(tid);
495 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
496 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
498 info = (struct startup_info *)(teb + 1);
500 info->entry_point = start;
501 info->entry_arg = param;
503 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
504 thread_data->request_fd = request_pipe[1];
505 thread_data->reply_fd = -1;
506 thread_data->wait_fd[0] = -1;
507 thread_data->wait_fd[1] = -1;
509 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
511 pthread_attr_init( &attr );
512 pthread_attr_setstack( &attr, teb->DeallocationStack,
513 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
514 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
515 interlocked_xchg_add( &nb_threads, 1 );
516 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
518 interlocked_xchg_add( &nb_threads, -1 );
519 pthread_attr_destroy( &attr );
520 status = STATUS_NO_MEMORY;
523 pthread_attr_destroy( &attr );
524 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
526 if (id) id->UniqueThread = ULongToHandle(tid);
527 if (handle_ptr) *handle_ptr = handle;
528 else NtClose( handle );
530 return STATUS_SUCCESS;
533 if (teb) signal_free_thread( teb );
534 if (handle) NtClose( handle );
535 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
536 close( request_pipe[1] );
541 /******************************************************************************
542 * RtlGetNtGlobalFlags (NTDLL.@)
544 ULONG WINAPI RtlGetNtGlobalFlags(void)
546 if (!peb) return 0; /* init not done yet */
547 return peb->NtGlobalFlag;
551 /***********************************************************************
552 * NtOpenThread (NTDLL.@)
553 * ZwOpenThread (NTDLL.@)
555 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
556 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
560 SERVER_START_REQ( open_thread )
562 req->tid = HandleToULong(id->UniqueThread);
563 req->access = access;
564 req->attributes = attr ? attr->Attributes : 0;
565 ret = wine_server_call( req );
566 *handle = wine_server_ptr_handle( reply->handle );
573 /******************************************************************************
574 * NtSuspendThread (NTDLL.@)
575 * ZwSuspendThread (NTDLL.@)
577 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
581 SERVER_START_REQ( suspend_thread )
583 req->handle = wine_server_obj_handle( handle );
584 if (!(ret = wine_server_call( req ))) *count = reply->count;
591 /******************************************************************************
592 * NtResumeThread (NTDLL.@)
593 * ZwResumeThread (NTDLL.@)
595 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
599 SERVER_START_REQ( resume_thread )
601 req->handle = wine_server_obj_handle( handle );
602 if (!(ret = wine_server_call( req ))) *count = reply->count;
609 /******************************************************************************
610 * NtAlertResumeThread (NTDLL.@)
611 * ZwAlertResumeThread (NTDLL.@)
613 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
615 FIXME( "stub: should alert thread %p\n", handle );
616 return NtResumeThread( handle, count );
620 /******************************************************************************
621 * NtAlertThread (NTDLL.@)
622 * ZwAlertThread (NTDLL.@)
624 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
626 FIXME( "stub: %p\n", handle );
627 return STATUS_NOT_IMPLEMENTED;
631 /******************************************************************************
632 * NtTerminateThread (NTDLL.@)
633 * ZwTerminateThread (NTDLL.@)
635 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
640 SERVER_START_REQ( terminate_thread )
642 req->handle = wine_server_obj_handle( handle );
643 req->exit_code = exit_code;
644 ret = wine_server_call( req );
645 self = !ret && reply->self;
649 if (self) abort_thread( exit_code );
654 /******************************************************************************
655 * NtQueueApcThread (NTDLL.@)
657 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
658 ULONG_PTR arg2, ULONG_PTR arg3 )
661 SERVER_START_REQ( queue_apc )
663 req->handle = wine_server_obj_handle( handle );
666 req->call.type = APC_USER;
667 req->call.user.func = wine_server_client_ptr( func );
668 req->call.user.args[0] = arg1;
669 req->call.user.args[1] = arg2;
670 req->call.user.args[2] = arg3;
672 else req->call.type = APC_NONE; /* wake up only */
673 ret = wine_server_call( req );
680 /***********************************************************************
681 * NtSetContextThread (NTDLL.@)
682 * ZwSetContextThread (NTDLL.@)
684 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
691 /* on i386 debug registers always require a server call */
692 self = (handle == GetCurrentThread());
693 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
695 self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
696 ntdll_get_thread_data()->dr1 == context->Dr1 &&
697 ntdll_get_thread_data()->dr2 == context->Dr2 &&
698 ntdll_get_thread_data()->dr3 == context->Dr3 &&
699 ntdll_get_thread_data()->dr6 == context->Dr6 &&
700 ntdll_get_thread_data()->dr7 == context->Dr7);
706 context_t server_context;
708 context_to_server( &server_context, context );
710 SERVER_START_REQ( set_thread_context )
712 req->handle = wine_server_obj_handle( handle );
714 wine_server_add_data( req, &server_context, sizeof(server_context) );
715 ret = wine_server_call( req );
720 if (ret == STATUS_PENDING)
722 for (i = 0; i < 100; i++)
724 SERVER_START_REQ( set_thread_context )
726 req->handle = wine_server_obj_handle( handle );
728 wine_server_add_data( req, &server_context, sizeof(server_context) );
729 ret = wine_server_call( req );
732 if (ret == STATUS_PENDING)
734 LARGE_INTEGER timeout;
735 timeout.QuadPart = -10000;
736 NtDelayExecution( FALSE, &timeout );
740 NtResumeThread( handle, &dummy );
741 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
747 if (self) set_cpu_context( context );
748 return STATUS_SUCCESS;
752 /* convert CPU-specific flags to generic server flags */
753 static inline unsigned int get_server_context_flags( DWORD flags )
755 unsigned int ret = 0;
757 flags &= 0x3f; /* mask CPU id flags */
758 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
759 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
760 #ifdef CONTEXT_SEGMENTS
761 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
763 #ifdef CONTEXT_FLOATING_POINT
764 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
766 #ifdef CONTEXT_DEBUG_REGISTERS
767 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
769 #ifdef CONTEXT_EXTENDED_REGISTERS
770 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
775 /***********************************************************************
776 * NtGetContextThread (NTDLL.@)
777 * ZwGetContextThread (NTDLL.@)
779 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
783 DWORD needed_flags = context->ContextFlags;
784 BOOL self = (handle == GetCurrentThread());
787 /* on i386 debug registers always require a server call */
788 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
793 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
794 context_t server_context;
796 SERVER_START_REQ( get_thread_context )
798 req->handle = wine_server_obj_handle( handle );
799 req->flags = server_flags;
801 wine_server_set_reply( req, &server_context, sizeof(server_context) );
802 ret = wine_server_call( req );
807 if (ret == STATUS_PENDING)
809 for (i = 0; i < 100; i++)
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 );
820 if (ret == STATUS_PENDING)
822 LARGE_INTEGER timeout;
823 timeout.QuadPart = -10000;
824 NtDelayExecution( FALSE, &timeout );
828 NtResumeThread( handle, &dummy );
829 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
831 if (!ret) ret = context_from_server( context, &server_context );
833 needed_flags &= ~context->ContextFlags;
841 RtlCaptureContext( &ctx );
842 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
843 context->ContextFlags |= ctx.ContextFlags & needed_flags;
846 /* update the cached version of the debug registers */
847 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
849 ntdll_get_thread_data()->dr0 = context->Dr0;
850 ntdll_get_thread_data()->dr1 = context->Dr1;
851 ntdll_get_thread_data()->dr2 = context->Dr2;
852 ntdll_get_thread_data()->dr3 = context->Dr3;
853 ntdll_get_thread_data()->dr6 = context->Dr6;
854 ntdll_get_thread_data()->dr7 = context->Dr7;
858 return STATUS_SUCCESS;
862 /******************************************************************************
863 * NtQueryInformationThread (NTDLL.@)
864 * ZwQueryInformationThread (NTDLL.@)
866 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
867 void *data, ULONG length, ULONG *ret_len )
873 case ThreadBasicInformation:
875 THREAD_BASIC_INFORMATION info;
876 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
878 SERVER_START_REQ( get_thread_info )
880 req->handle = wine_server_obj_handle( handle );
882 if (!(status = wine_server_call( req )))
884 info.ExitStatus = reply->exit_code;
885 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
886 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
887 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
888 info.AffinityMask = reply->affinity & affinity_mask;
889 info.Priority = reply->priority;
890 info.BasePriority = reply->priority; /* FIXME */
894 if (status == STATUS_SUCCESS)
896 if (data) memcpy( data, &info, min( length, sizeof(info) ));
897 if (ret_len) *ret_len = min( length, sizeof(info) );
901 case ThreadAffinityMask:
903 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
904 ULONG_PTR affinity = 0;
906 SERVER_START_REQ( get_thread_info )
908 req->handle = wine_server_obj_handle( handle );
910 if (!(status = wine_server_call( req )))
911 affinity = reply->affinity & affinity_mask;
914 if (status == STATUS_SUCCESS)
916 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
917 if (ret_len) *ret_len = min( length, sizeof(affinity) );
923 KERNEL_USER_TIMES kusrt;
924 /* We need to do a server call to get the creation time or exit time */
925 /* This works on any thread */
926 SERVER_START_REQ( get_thread_info )
928 req->handle = wine_server_obj_handle( handle );
930 status = wine_server_call( req );
931 if (status == STATUS_SUCCESS)
933 kusrt.CreateTime.QuadPart = reply->creation_time;
934 kusrt.ExitTime.QuadPart = reply->exit_time;
938 if (status == STATUS_SUCCESS)
940 /* We call times(2) for kernel time or user time */
941 /* We can only (portably) do this for the current thread */
942 if (handle == GetCurrentThread())
945 long clocks_per_sec = sysconf(_SC_CLK_TCK);
948 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
949 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
953 static BOOL reported = FALSE;
955 kusrt.KernelTime.QuadPart = 0;
956 kusrt.UserTime.QuadPart = 0;
958 TRACE("Cannot get kerneltime or usertime of other threads\n");
961 FIXME("Cannot get kerneltime or usertime of other threads\n");
965 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
966 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
970 case ThreadDescriptorTableEntry:
973 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
974 if (length < sizeof(*tdi))
975 status = STATUS_INFO_LENGTH_MISMATCH;
976 else if (!(tdi->Selector & 4)) /* GDT selector */
978 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
979 status = STATUS_SUCCESS;
980 if (!sel) /* null selector */
981 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
984 tdi->Entry.BaseLow = 0;
985 tdi->Entry.HighWord.Bits.BaseMid = 0;
986 tdi->Entry.HighWord.Bits.BaseHi = 0;
987 tdi->Entry.LimitLow = 0xffff;
988 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
989 tdi->Entry.HighWord.Bits.Dpl = 3;
990 tdi->Entry.HighWord.Bits.Sys = 0;
991 tdi->Entry.HighWord.Bits.Pres = 1;
992 tdi->Entry.HighWord.Bits.Granularity = 1;
993 tdi->Entry.HighWord.Bits.Default_Big = 1;
994 tdi->Entry.HighWord.Bits.Type = 0x12;
995 /* it has to be one of the system GDT selectors */
996 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
998 if (sel == (wine_get_cs() & ~3))
999 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1000 else status = STATUS_ACCESS_DENIED;
1006 SERVER_START_REQ( get_selector_entry )
1008 req->handle = wine_server_obj_handle( handle );
1009 req->entry = tdi->Selector >> 3;
1010 status = wine_server_call( req );
1013 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1014 status = STATUS_ACCESS_VIOLATION;
1017 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1018 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1019 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1025 if (status == STATUS_SUCCESS && ret_len)
1026 /* yes, that's a bit strange, but it's the way it is */
1027 *ret_len = sizeof(LDT_ENTRY);
1029 status = STATUS_NOT_IMPLEMENTED;
1033 case ThreadAmILastThread:
1035 SERVER_START_REQ(get_thread_info)
1037 req->handle = wine_server_obj_handle( handle );
1039 status = wine_server_call( req );
1040 if (status == STATUS_SUCCESS)
1042 BOOLEAN last = reply->last;
1043 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1044 if (ret_len) *ret_len = min( length, sizeof(last) );
1050 case ThreadPriority:
1051 case ThreadBasePriority:
1052 case ThreadImpersonationToken:
1053 case ThreadEnableAlignmentFaultFixup:
1054 case ThreadEventPair_Reusable:
1055 case ThreadQuerySetWin32StartAddress:
1056 case ThreadZeroTlsCell:
1057 case ThreadPerformanceCount:
1058 case ThreadIdealProcessor:
1059 case ThreadPriorityBoost:
1060 case ThreadSetTlsArrayAddress:
1061 case ThreadIsIoPending:
1063 FIXME( "info class %d not supported yet\n", class );
1064 return STATUS_NOT_IMPLEMENTED;
1069 /******************************************************************************
1070 * NtSetInformationThread (NTDLL.@)
1071 * ZwSetInformationThread (NTDLL.@)
1073 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1074 LPCVOID data, ULONG length )
1079 case ThreadZeroTlsCell:
1080 if (handle == GetCurrentThread())
1085 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1086 index = *(const DWORD *)data;
1087 if (index < TLS_MINIMUM_AVAILABLE)
1089 RtlAcquirePebLock();
1090 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1092 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1093 teb->TlsSlots[index] = 0;
1095 RtlReleasePebLock();
1099 index -= TLS_MINIMUM_AVAILABLE;
1100 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1101 return STATUS_INVALID_PARAMETER;
1102 RtlAcquirePebLock();
1103 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1105 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1106 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1108 RtlReleasePebLock();
1110 return STATUS_SUCCESS;
1112 FIXME( "ZeroTlsCell not supported on other threads\n" );
1113 return STATUS_NOT_IMPLEMENTED;
1115 case ThreadImpersonationToken:
1117 const HANDLE *phToken = data;
1118 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1119 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1120 SERVER_START_REQ( set_thread_info )
1122 req->handle = wine_server_obj_handle( handle );
1123 req->token = wine_server_obj_handle( *phToken );
1124 req->mask = SET_THREAD_INFO_TOKEN;
1125 status = wine_server_call( req );
1130 case ThreadBasePriority:
1132 const DWORD *pprio = data;
1133 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1134 SERVER_START_REQ( set_thread_info )
1136 req->handle = wine_server_obj_handle( handle );
1137 req->priority = *pprio;
1138 req->mask = SET_THREAD_INFO_PRIORITY;
1139 status = wine_server_call( req );
1144 case ThreadAffinityMask:
1146 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1149 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1150 req_aff = *(const ULONG_PTR *)data;
1151 if ((ULONG)req_aff == ~0u) req_aff = affinity_mask;
1152 else if (req_aff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1153 else if (!req_aff) return STATUS_INVALID_PARAMETER;
1154 SERVER_START_REQ( set_thread_info )
1156 req->handle = wine_server_obj_handle( handle );
1157 req->affinity = req_aff;
1158 req->mask = SET_THREAD_INFO_AFFINITY;
1159 status = wine_server_call( req );
1164 case ThreadHideFromDebugger:
1165 /* pretend the call succeeded to satisfy some code protectors */
1166 return STATUS_SUCCESS;
1168 case ThreadBasicInformation:
1170 case ThreadPriority:
1171 case ThreadDescriptorTableEntry:
1172 case ThreadEnableAlignmentFaultFixup:
1173 case ThreadEventPair_Reusable:
1174 case ThreadQuerySetWin32StartAddress:
1175 case ThreadPerformanceCount:
1176 case ThreadAmILastThread:
1177 case ThreadIdealProcessor:
1178 case ThreadPriorityBoost:
1179 case ThreadSetTlsArrayAddress:
1180 case ThreadIsIoPending:
1182 FIXME( "info class %d not supported yet\n", class );
1183 return STATUS_NOT_IMPLEMENTED;
1187 /******************************************************************************
1188 * NtGetCurrentProcessorNumber (NTDLL.@)
1190 * Return the processor, on which the thread is running
1193 ULONG WINAPI NtGetCurrentProcessorNumber(void)
1197 #if defined(__linux__) && defined(__NR_getcpu)
1198 int res = syscall(__NR_getcpu, &processor, NULL, NULL);
1199 if (res != -1) return processor;
1202 if (NtCurrentTeb()->Peb->NumberOfProcessors > 1)
1204 ULONG_PTR thread_mask, processor_mask;
1207 status = NtQueryInformationThread(GetCurrentThread(), ThreadAffinityMask,
1208 &thread_mask, sizeof(thread_mask), NULL);
1209 if (status == STATUS_SUCCESS)
1211 for (processor = 0; processor < NtCurrentTeb()->Peb->NumberOfProcessors; processor++)
1213 processor_mask = (1 << processor);
1214 if (thread_mask & processor_mask)
1216 if (thread_mask != processor_mask)
1217 FIXME("need multicore support (%d processors)\n",
1218 NtCurrentTeb()->Peb->NumberOfProcessors);
1225 /* fallback to the first processor */