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 (RtlDllShutdownInProgress()) return STATUS_ACCESS_DENIED;
466 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
467 wine_server_send_fd( request_pipe[0] );
469 SERVER_START_REQ( new_thread )
471 req->access = THREAD_ALL_ACCESS;
472 req->attributes = 0; /* FIXME */
473 req->suspend = suspended;
474 req->request_fd = request_pipe[0];
475 if (!(status = wine_server_call( req )))
477 handle = wine_server_ptr_handle( reply->handle );
480 close( request_pipe[0] );
486 close( request_pipe[1] );
490 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
492 if ((status = signal_alloc_thread( &teb ))) goto error;
494 teb->Peb = NtCurrentTeb()->Peb;
495 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
496 teb->ClientId.UniqueThread = ULongToHandle(tid);
497 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
498 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
500 info = (struct startup_info *)(teb + 1);
502 info->entry_point = start;
503 info->entry_arg = param;
505 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
506 thread_data->request_fd = request_pipe[1];
507 thread_data->reply_fd = -1;
508 thread_data->wait_fd[0] = -1;
509 thread_data->wait_fd[1] = -1;
511 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
513 pthread_attr_init( &attr );
514 pthread_attr_setstack( &attr, teb->DeallocationStack,
515 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
516 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
517 interlocked_xchg_add( &nb_threads, 1 );
518 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
520 interlocked_xchg_add( &nb_threads, -1 );
521 pthread_attr_destroy( &attr );
522 status = STATUS_NO_MEMORY;
525 pthread_attr_destroy( &attr );
526 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
528 if (id) id->UniqueThread = ULongToHandle(tid);
529 if (handle_ptr) *handle_ptr = handle;
530 else NtClose( handle );
532 return STATUS_SUCCESS;
535 if (teb) signal_free_thread( teb );
536 if (handle) NtClose( handle );
537 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
538 close( request_pipe[1] );
543 /******************************************************************************
544 * RtlGetNtGlobalFlags (NTDLL.@)
546 ULONG WINAPI RtlGetNtGlobalFlags(void)
548 if (!peb) return 0; /* init not done yet */
549 return peb->NtGlobalFlag;
553 /***********************************************************************
554 * NtOpenThread (NTDLL.@)
555 * ZwOpenThread (NTDLL.@)
557 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
558 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
562 SERVER_START_REQ( open_thread )
564 req->tid = HandleToULong(id->UniqueThread);
565 req->access = access;
566 req->attributes = attr ? attr->Attributes : 0;
567 ret = wine_server_call( req );
568 *handle = wine_server_ptr_handle( reply->handle );
575 /******************************************************************************
576 * NtSuspendThread (NTDLL.@)
577 * ZwSuspendThread (NTDLL.@)
579 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
583 SERVER_START_REQ( suspend_thread )
585 req->handle = wine_server_obj_handle( handle );
586 if (!(ret = wine_server_call( req ))) *count = reply->count;
593 /******************************************************************************
594 * NtResumeThread (NTDLL.@)
595 * ZwResumeThread (NTDLL.@)
597 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
601 SERVER_START_REQ( resume_thread )
603 req->handle = wine_server_obj_handle( handle );
604 if (!(ret = wine_server_call( req ))) *count = reply->count;
611 /******************************************************************************
612 * NtAlertResumeThread (NTDLL.@)
613 * ZwAlertResumeThread (NTDLL.@)
615 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
617 FIXME( "stub: should alert thread %p\n", handle );
618 return NtResumeThread( handle, count );
622 /******************************************************************************
623 * NtAlertThread (NTDLL.@)
624 * ZwAlertThread (NTDLL.@)
626 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
628 FIXME( "stub: %p\n", handle );
629 return STATUS_NOT_IMPLEMENTED;
633 /******************************************************************************
634 * NtTerminateThread (NTDLL.@)
635 * ZwTerminateThread (NTDLL.@)
637 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
642 SERVER_START_REQ( terminate_thread )
644 req->handle = wine_server_obj_handle( handle );
645 req->exit_code = exit_code;
646 ret = wine_server_call( req );
647 self = !ret && reply->self;
651 if (self) abort_thread( exit_code );
656 /******************************************************************************
657 * NtQueueApcThread (NTDLL.@)
659 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
660 ULONG_PTR arg2, ULONG_PTR arg3 )
663 SERVER_START_REQ( queue_apc )
665 req->handle = wine_server_obj_handle( handle );
668 req->call.type = APC_USER;
669 req->call.user.func = wine_server_client_ptr( func );
670 req->call.user.args[0] = arg1;
671 req->call.user.args[1] = arg2;
672 req->call.user.args[2] = arg3;
674 else req->call.type = APC_NONE; /* wake up only */
675 ret = wine_server_call( req );
682 /***********************************************************************
683 * NtSetContextThread (NTDLL.@)
684 * ZwSetContextThread (NTDLL.@)
686 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
693 /* on i386 debug registers always require a server call */
694 self = (handle == GetCurrentThread());
695 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
697 self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
698 ntdll_get_thread_data()->dr1 == context->Dr1 &&
699 ntdll_get_thread_data()->dr2 == context->Dr2 &&
700 ntdll_get_thread_data()->dr3 == context->Dr3 &&
701 ntdll_get_thread_data()->dr6 == context->Dr6 &&
702 ntdll_get_thread_data()->dr7 == context->Dr7);
708 context_t server_context;
710 context_to_server( &server_context, context );
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 );
722 if (ret == STATUS_PENDING)
724 for (i = 0; i < 100; i++)
726 SERVER_START_REQ( set_thread_context )
728 req->handle = wine_server_obj_handle( handle );
730 wine_server_add_data( req, &server_context, sizeof(server_context) );
731 ret = wine_server_call( req );
734 if (ret == STATUS_PENDING)
736 LARGE_INTEGER timeout;
737 timeout.QuadPart = -10000;
738 NtDelayExecution( FALSE, &timeout );
742 NtResumeThread( handle, &dummy );
743 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
749 if (self) set_cpu_context( context );
750 return STATUS_SUCCESS;
754 /* convert CPU-specific flags to generic server flags */
755 static inline unsigned int get_server_context_flags( DWORD flags )
757 unsigned int ret = 0;
759 flags &= 0x3f; /* mask CPU id flags */
760 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
761 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
762 #ifdef CONTEXT_SEGMENTS
763 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
765 #ifdef CONTEXT_FLOATING_POINT
766 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
768 #ifdef CONTEXT_DEBUG_REGISTERS
769 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
771 #ifdef CONTEXT_EXTENDED_REGISTERS
772 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
777 /***********************************************************************
778 * NtGetContextThread (NTDLL.@)
779 * ZwGetContextThread (NTDLL.@)
781 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
785 DWORD needed_flags = context->ContextFlags;
786 BOOL self = (handle == GetCurrentThread());
789 /* on i386 debug registers always require a server call */
790 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
795 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
796 context_t server_context;
798 SERVER_START_REQ( get_thread_context )
800 req->handle = wine_server_obj_handle( handle );
801 req->flags = server_flags;
803 wine_server_set_reply( req, &server_context, sizeof(server_context) );
804 ret = wine_server_call( req );
809 if (ret == STATUS_PENDING)
811 for (i = 0; i < 100; i++)
813 SERVER_START_REQ( get_thread_context )
815 req->handle = wine_server_obj_handle( handle );
816 req->flags = server_flags;
818 wine_server_set_reply( req, &server_context, sizeof(server_context) );
819 ret = wine_server_call( req );
822 if (ret == STATUS_PENDING)
824 LARGE_INTEGER timeout;
825 timeout.QuadPart = -10000;
826 NtDelayExecution( FALSE, &timeout );
830 NtResumeThread( handle, &dummy );
831 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
833 if (!ret) ret = context_from_server( context, &server_context );
835 needed_flags &= ~context->ContextFlags;
843 RtlCaptureContext( &ctx );
844 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
845 context->ContextFlags |= ctx.ContextFlags & needed_flags;
848 /* update the cached version of the debug registers */
849 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
851 ntdll_get_thread_data()->dr0 = context->Dr0;
852 ntdll_get_thread_data()->dr1 = context->Dr1;
853 ntdll_get_thread_data()->dr2 = context->Dr2;
854 ntdll_get_thread_data()->dr3 = context->Dr3;
855 ntdll_get_thread_data()->dr6 = context->Dr6;
856 ntdll_get_thread_data()->dr7 = context->Dr7;
860 return STATUS_SUCCESS;
864 /******************************************************************************
865 * NtQueryInformationThread (NTDLL.@)
866 * ZwQueryInformationThread (NTDLL.@)
868 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
869 void *data, ULONG length, ULONG *ret_len )
875 case ThreadBasicInformation:
877 THREAD_BASIC_INFORMATION info;
878 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
880 SERVER_START_REQ( get_thread_info )
882 req->handle = wine_server_obj_handle( handle );
884 if (!(status = wine_server_call( req )))
886 info.ExitStatus = reply->exit_code;
887 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
888 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
889 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
890 info.AffinityMask = reply->affinity & affinity_mask;
891 info.Priority = reply->priority;
892 info.BasePriority = reply->priority; /* FIXME */
896 if (status == STATUS_SUCCESS)
898 if (data) memcpy( data, &info, min( length, sizeof(info) ));
899 if (ret_len) *ret_len = min( length, sizeof(info) );
903 case ThreadAffinityMask:
905 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
906 ULONG_PTR affinity = 0;
908 SERVER_START_REQ( get_thread_info )
910 req->handle = wine_server_obj_handle( handle );
912 if (!(status = wine_server_call( req )))
913 affinity = reply->affinity & affinity_mask;
916 if (status == STATUS_SUCCESS)
918 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
919 if (ret_len) *ret_len = min( length, sizeof(affinity) );
925 KERNEL_USER_TIMES kusrt;
926 /* We need to do a server call to get the creation time or exit time */
927 /* This works on any thread */
928 SERVER_START_REQ( get_thread_info )
930 req->handle = wine_server_obj_handle( handle );
932 status = wine_server_call( req );
933 if (status == STATUS_SUCCESS)
935 kusrt.CreateTime.QuadPart = reply->creation_time;
936 kusrt.ExitTime.QuadPart = reply->exit_time;
940 if (status == STATUS_SUCCESS)
942 /* We call times(2) for kernel time or user time */
943 /* We can only (portably) do this for the current thread */
944 if (handle == GetCurrentThread())
947 long clocks_per_sec = sysconf(_SC_CLK_TCK);
950 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
951 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
955 static BOOL reported = FALSE;
957 kusrt.KernelTime.QuadPart = 0;
958 kusrt.UserTime.QuadPart = 0;
960 TRACE("Cannot get kerneltime or usertime of other threads\n");
963 FIXME("Cannot get kerneltime or usertime of other threads\n");
967 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
968 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
972 case ThreadDescriptorTableEntry:
975 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
976 if (length < sizeof(*tdi))
977 status = STATUS_INFO_LENGTH_MISMATCH;
978 else if (!(tdi->Selector & 4)) /* GDT selector */
980 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
981 status = STATUS_SUCCESS;
982 if (!sel) /* null selector */
983 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
986 tdi->Entry.BaseLow = 0;
987 tdi->Entry.HighWord.Bits.BaseMid = 0;
988 tdi->Entry.HighWord.Bits.BaseHi = 0;
989 tdi->Entry.LimitLow = 0xffff;
990 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
991 tdi->Entry.HighWord.Bits.Dpl = 3;
992 tdi->Entry.HighWord.Bits.Sys = 0;
993 tdi->Entry.HighWord.Bits.Pres = 1;
994 tdi->Entry.HighWord.Bits.Granularity = 1;
995 tdi->Entry.HighWord.Bits.Default_Big = 1;
996 tdi->Entry.HighWord.Bits.Type = 0x12;
997 /* it has to be one of the system GDT selectors */
998 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1000 if (sel == (wine_get_cs() & ~3))
1001 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1002 else status = STATUS_ACCESS_DENIED;
1008 SERVER_START_REQ( get_selector_entry )
1010 req->handle = wine_server_obj_handle( handle );
1011 req->entry = tdi->Selector >> 3;
1012 status = wine_server_call( req );
1015 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1016 status = STATUS_ACCESS_VIOLATION;
1019 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1020 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1021 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1027 if (status == STATUS_SUCCESS && ret_len)
1028 /* yes, that's a bit strange, but it's the way it is */
1029 *ret_len = sizeof(LDT_ENTRY);
1031 status = STATUS_NOT_IMPLEMENTED;
1035 case ThreadAmILastThread:
1037 SERVER_START_REQ(get_thread_info)
1039 req->handle = wine_server_obj_handle( handle );
1041 status = wine_server_call( req );
1042 if (status == STATUS_SUCCESS)
1044 BOOLEAN last = reply->last;
1045 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1046 if (ret_len) *ret_len = min( length, sizeof(last) );
1052 case ThreadPriority:
1053 case ThreadBasePriority:
1054 case ThreadImpersonationToken:
1055 case ThreadEnableAlignmentFaultFixup:
1056 case ThreadEventPair_Reusable:
1057 case ThreadQuerySetWin32StartAddress:
1058 case ThreadZeroTlsCell:
1059 case ThreadPerformanceCount:
1060 case ThreadIdealProcessor:
1061 case ThreadPriorityBoost:
1062 case ThreadSetTlsArrayAddress:
1063 case ThreadIsIoPending:
1065 FIXME( "info class %d not supported yet\n", class );
1066 return STATUS_NOT_IMPLEMENTED;
1071 /******************************************************************************
1072 * NtSetInformationThread (NTDLL.@)
1073 * ZwSetInformationThread (NTDLL.@)
1075 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1076 LPCVOID data, ULONG length )
1081 case ThreadZeroTlsCell:
1082 if (handle == GetCurrentThread())
1087 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1088 index = *(const DWORD *)data;
1089 if (index < TLS_MINIMUM_AVAILABLE)
1091 RtlAcquirePebLock();
1092 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1094 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1095 teb->TlsSlots[index] = 0;
1097 RtlReleasePebLock();
1101 index -= TLS_MINIMUM_AVAILABLE;
1102 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1103 return STATUS_INVALID_PARAMETER;
1104 RtlAcquirePebLock();
1105 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1107 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1108 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1110 RtlReleasePebLock();
1112 return STATUS_SUCCESS;
1114 FIXME( "ZeroTlsCell not supported on other threads\n" );
1115 return STATUS_NOT_IMPLEMENTED;
1117 case ThreadImpersonationToken:
1119 const HANDLE *phToken = data;
1120 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1121 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1122 SERVER_START_REQ( set_thread_info )
1124 req->handle = wine_server_obj_handle( handle );
1125 req->token = wine_server_obj_handle( *phToken );
1126 req->mask = SET_THREAD_INFO_TOKEN;
1127 status = wine_server_call( req );
1132 case ThreadBasePriority:
1134 const DWORD *pprio = data;
1135 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1136 SERVER_START_REQ( set_thread_info )
1138 req->handle = wine_server_obj_handle( handle );
1139 req->priority = *pprio;
1140 req->mask = SET_THREAD_INFO_PRIORITY;
1141 status = wine_server_call( req );
1146 case ThreadAffinityMask:
1148 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1151 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1152 req_aff = *(const ULONG_PTR *)data;
1153 if ((ULONG)req_aff == ~0u) req_aff = affinity_mask;
1154 else if (req_aff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1155 else if (!req_aff) return STATUS_INVALID_PARAMETER;
1156 SERVER_START_REQ( set_thread_info )
1158 req->handle = wine_server_obj_handle( handle );
1159 req->affinity = req_aff;
1160 req->mask = SET_THREAD_INFO_AFFINITY;
1161 status = wine_server_call( req );
1166 case ThreadHideFromDebugger:
1167 /* pretend the call succeeded to satisfy some code protectors */
1168 return STATUS_SUCCESS;
1170 case ThreadBasicInformation:
1172 case ThreadPriority:
1173 case ThreadDescriptorTableEntry:
1174 case ThreadEnableAlignmentFaultFixup:
1175 case ThreadEventPair_Reusable:
1176 case ThreadQuerySetWin32StartAddress:
1177 case ThreadPerformanceCount:
1178 case ThreadAmILastThread:
1179 case ThreadIdealProcessor:
1180 case ThreadPriorityBoost:
1181 case ThreadSetTlsArrayAddress:
1182 case ThreadIsIoPending:
1184 FIXME( "info class %d not supported yet\n", class );
1185 return STATUS_NOT_IMPLEMENTED;
1189 /******************************************************************************
1190 * NtGetCurrentProcessorNumber (NTDLL.@)
1192 * Return the processor, on which the thread is running
1195 ULONG WINAPI NtGetCurrentProcessorNumber(void)
1199 #if defined(__linux__) && defined(__NR_getcpu)
1200 int res = syscall(__NR_getcpu, &processor, NULL, NULL);
1201 if (res != -1) return processor;
1204 if (NtCurrentTeb()->Peb->NumberOfProcessors > 1)
1206 ULONG_PTR thread_mask, processor_mask;
1209 status = NtQueryInformationThread(GetCurrentThread(), ThreadAffinityMask,
1210 &thread_mask, sizeof(thread_mask), NULL);
1211 if (status == STATUS_SUCCESS)
1213 for (processor = 0; processor < NtCurrentTeb()->Peb->NumberOfProcessors; processor++)
1215 processor_mask = (1 << processor);
1216 if (thread_mask & processor_mask)
1218 if (thread_mask != processor_mask)
1219 FIXME("need multicore support (%d processors)\n",
1220 NtCurrentTeb()->Peb->NumberOfProcessors);
1227 /* fallback to the first processor */