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"
25 #include <sys/types.h>
26 #ifdef HAVE_SYS_MMAN_H
29 #ifdef HAVE_SYS_TIMES_H
30 #include <sys/times.h>
33 #define NONAMELESSUNION
35 #define WIN32_NO_STATUS
38 #include "wine/library.h"
39 #include "wine/server.h"
40 #include "wine/pthread.h"
41 #include "wine/debug.h"
42 #include "ntdll_misc.h"
44 #include "wine/exception.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(thread);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
51 /* info passed to a starting thread */
54 struct wine_pthread_thread_info pthread_info;
55 PRTL_THREAD_START_ROUTINE entry_point;
59 static PEB_LDR_DATA ldr;
60 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
61 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
62 static RTL_BITMAP tls_bitmap;
63 static RTL_BITMAP tls_expansion_bitmap;
64 static LIST_ENTRY tls_links;
65 static size_t sigstack_total_size;
66 static ULONG sigstack_zero_bits;
68 struct wine_pthread_functions pthread_functions = { NULL };
71 static RTL_CRITICAL_SECTION ldt_section;
72 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
75 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
76 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
78 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
79 static sigset_t ldt_sigset;
81 /***********************************************************************
82 * locking for LDT routines
84 static void ldt_lock(void)
88 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
89 RtlEnterCriticalSection( &ldt_section );
90 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
93 static void ldt_unlock(void)
95 if (ldt_section.RecursionCount == 1)
97 sigset_t sigset = ldt_sigset;
98 RtlLeaveCriticalSection( &ldt_section );
99 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
101 else RtlLeaveCriticalSection( &ldt_section );
105 /***********************************************************************
108 static inline NTSTATUS init_teb( TEB *teb )
110 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
112 teb->Tib.ExceptionList = (void *)~0UL;
113 teb->Tib.StackBase = (void *)~0UL;
114 teb->Tib.Self = &teb->Tib;
115 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
116 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
118 if (!(thread_data->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
119 thread_data->request_fd = -1;
120 thread_data->reply_fd = -1;
121 thread_data->wait_fd[0] = -1;
122 thread_data->wait_fd[1] = -1;
124 return STATUS_SUCCESS;
128 /***********************************************************************
131 * Make sure the unicode string doesn't point beyond the end pointer
133 static inline void fix_unicode_string( UNICODE_STRING *str, const char *end_ptr )
135 if ((char *)str->Buffer >= end_ptr)
137 str->Length = str->MaximumLength = 0;
141 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
143 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
145 if (str->Length >= str->MaximumLength)
147 if (str->MaximumLength >= sizeof(WCHAR))
148 str->Length = str->MaximumLength - sizeof(WCHAR);
150 str->Length = str->MaximumLength = 0;
155 /***********************************************************************
156 * init_user_process_params
158 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
160 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
165 RTL_USER_PROCESS_PARAMETERS *params = NULL;
167 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &info_size,
168 MEM_COMMIT, PAGE_READWRITE );
169 if (status != STATUS_SUCCESS) return status;
171 params->AllocationSize = info_size;
172 NtCurrentTeb()->Peb->ProcessParameters = params;
174 SERVER_START_REQ( get_startup_info )
176 wine_server_set_reply( req, params, info_size );
177 if (!(status = wine_server_call( req )))
179 info_size = wine_server_reply_size( reply );
180 *exe_file = reply->exe_file;
181 params->hStdInput = reply->hstdin;
182 params->hStdOutput = reply->hstdout;
183 params->hStdError = reply->hstderr;
187 if (status != STATUS_SUCCESS) return status;
189 if (params->Size > info_size) params->Size = info_size;
191 /* make sure the strings are valid */
192 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
193 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
194 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
195 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
196 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
197 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
198 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
199 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
201 /* environment needs to be a separate memory block */
202 env_size = info_size - params->Size;
203 if (!env_size) env_size = 1;
205 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
206 MEM_COMMIT, PAGE_READWRITE );
207 if (status != STATUS_SUCCESS) return status;
208 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
209 params->Environment = ptr;
211 RtlNormalizeProcessParams( params );
216 /***********************************************************************
219 * Setup the initial thread.
221 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
223 HANDLE thread_init(void)
228 SIZE_T size, info_size;
231 struct ntdll_thread_data *thread_data;
232 struct wine_pthread_thread_info thread_info;
233 static struct debug_info debug_info; /* debug info for initial thread */
237 /* reserve space for shared user data */
239 addr = (void *)0x7ffe0000;
241 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
242 user_shared_data = addr;
244 /* allocate and initialize the PEB */
248 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
249 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
252 peb->NumberOfProcessors = 1;
253 peb->ProcessParameters = ¶ms;
254 peb->TlsBitmap = &tls_bitmap;
255 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
257 params.CurrentDirectory.DosPath.Buffer = current_dir;
258 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
259 params.wShowWindow = 1; /* SW_SHOWNORMAL */
260 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
261 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
262 sizeof(peb->TlsExpansionBitmapBits) * 8 );
263 InitializeListHead( &ldr.InLoadOrderModuleList );
264 InitializeListHead( &ldr.InMemoryOrderModuleList );
265 InitializeListHead( &ldr.InInitializationOrderModuleList );
266 InitializeListHead( &tls_links );
268 /* allocate and initialize the initial TEB */
270 sigstack_total_size = get_signal_stack_total_size();
271 while (1 << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
272 assert( 1 << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
273 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
274 thread_info.teb_size = sigstack_total_size;
277 size = sigstack_total_size;
278 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
279 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
282 thread_info.teb_size = size;
284 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
285 thread_data->debug_info = &debug_info;
286 InsertHeadList( &tls_links, &teb->TlsLinks );
288 thread_info.stack_base = NULL;
289 thread_info.stack_size = 0;
290 thread_info.teb_base = teb;
291 thread_info.teb_sel = thread_data->fs;
292 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
293 pthread_functions.init_current_teb( &thread_info );
294 pthread_functions.init_thread( &thread_info );
295 virtual_init_threading();
297 debug_info.str_pos = debug_info.strings;
298 debug_info.out_pos = debug_info.output;
301 /* setup the server connection */
302 server_init_process();
303 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
305 /* create the process heap */
306 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
308 MESSAGE( "wine: failed to create the process heap\n" );
312 /* allocate user parameters */
315 init_user_process_params( info_size, &exe_file );
319 /* This is wine specific: we have no parent (we're started from unix)
320 * so, create a simple console with bare handles to unix stdio
322 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
323 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
324 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
327 /* initialize LDT locking */
328 wine_ldt_init_locking( ldt_lock, ldt_unlock );
330 /* initialize time values in user_shared_data */
331 NtQuerySystemTime( &now );
332 user_shared_data->SystemTime.LowPart = now.u.LowPart;
333 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
334 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
335 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
336 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
337 user_shared_data->TickCountMultiplier = 1 << 24;
342 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
343 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
345 static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
346 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
347 UNICODE_STRING module_name;
348 ANSI_STRING func_name;
349 HMODULE kernel32_handle;
351 if (unhandled_exception_filter) return unhandled_exception_filter;
353 RtlInitUnicodeString(&module_name, kernel32W);
354 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
356 if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
357 LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
358 (void **)&unhandled_exception_filter );
360 return unhandled_exception_filter;
364 /* wrapper for apps that don't declare the thread function correctly */
365 extern DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg );
366 __ASM_GLOBAL_FUNC(call_thread_entry_point,
371 "movl 8(%ebp),%eax\n\t"
376 static inline DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg )
378 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)entry;
383 /***********************************************************************
386 * Hack to make things compatible with the thread procedures used by kernel32.CreateThread.
388 static void DECLSPEC_NORETURN call_thread_func( PRTL_THREAD_START_ROUTINE rtl_func, void *arg )
393 MODULE_DllThreadAttach( NULL );
396 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), rtl_func, arg );
398 exit_code = call_thread_entry_point( rtl_func, arg );
400 /* send the exit code to the server */
401 SERVER_START_REQ( terminate_thread )
403 req->handle = GetCurrentThread();
404 req->exit_code = exit_code;
405 wine_server_call( req );
412 LdrShutdownProcess();
418 server_exit_thread( exit_code );
423 /***********************************************************************
426 * Startup routine for a newly created thread.
428 static void start_thread( struct wine_pthread_thread_info *info )
430 TEB *teb = info->teb_base;
431 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
432 struct startup_info *startup_info = (struct startup_info *)info;
433 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
434 void *arg = startup_info->entry_arg;
435 struct debug_info debug_info;
436 SIZE_T size, page_size = getpagesize();
438 debug_info.str_pos = debug_info.strings;
439 debug_info.out_pos = debug_info.output;
440 thread_data->debug_info = &debug_info;
442 pthread_functions.init_current_teb( info );
444 server_init_thread( info->pid, info->tid, func );
445 pthread_functions.init_thread( info );
447 /* allocate a memory view for the stack */
448 size = info->stack_size;
449 teb->DeallocationStack = info->stack_base;
450 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
451 &size, MEM_SYSTEM, PAGE_READWRITE );
452 /* limit is lower than base since the stack grows down */
453 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
454 teb->Tib.StackLimit = (char *)info->stack_base + page_size;
456 /* setup the guard page */
458 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
460 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
463 InsertHeadList( &tls_links, &teb->TlsLinks );
466 /* NOTE: Windows does not have an exception handler around the call to
467 * the thread attach. We do for ease of debugging */
468 if (get_unhandled_exception_filter())
472 call_thread_func( func, arg );
474 __EXCEPT(get_unhandled_exception_filter())
476 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
481 call_thread_func( func, arg );
485 /***********************************************************************
486 * RtlCreateUserThread (NTDLL.@)
488 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
489 BOOLEAN suspended, PVOID stack_addr,
490 SIZE_T stack_reserve, SIZE_T stack_commit,
491 PRTL_THREAD_START_ROUTINE start, void *param,
492 HANDLE *handle_ptr, CLIENT_ID *id )
495 struct ntdll_thread_data *thread_data = NULL;
496 struct ntdll_thread_regs *thread_regs;
497 struct startup_info *info = NULL;
504 SIZE_T size, page_size = getpagesize();
506 if (process != NtCurrentProcess())
511 call.create_thread.type = APC_CREATE_THREAD;
512 call.create_thread.func = start;
513 call.create_thread.arg = param;
514 call.create_thread.reserve = stack_reserve;
515 call.create_thread.commit = stack_commit;
516 call.create_thread.suspend = suspended;
517 status = NTDLL_queue_process_apc( process, &call, &result );
518 if (status != STATUS_SUCCESS) return status;
520 if (result.create_thread.status == STATUS_SUCCESS)
522 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
523 if (handle_ptr) *handle_ptr = result.create_thread.handle;
524 else NtClose( result.create_thread.handle );
526 return result.create_thread.status;
529 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
530 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
531 wine_server_send_fd( request_pipe[0] );
533 SERVER_START_REQ( new_thread )
535 req->access = THREAD_ALL_ACCESS;
536 req->attributes = 0; /* FIXME */
537 req->suspend = suspended;
538 req->request_fd = request_pipe[0];
539 if (!(status = wine_server_call( req )))
541 handle = reply->handle;
544 close( request_pipe[0] );
550 close( request_pipe[1] );
554 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
557 size = sigstack_total_size;
558 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
559 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
562 teb->Peb = NtCurrentTeb()->Peb;
563 info = (struct startup_info *)(teb + 1);
564 info->pthread_info.teb_size = size;
565 if ((status = init_teb( teb ))) goto error;
567 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
568 teb->ClientId.UniqueThread = ULongToHandle(tid);
570 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
571 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
572 thread_data->request_fd = request_pipe[1];
574 info->pthread_info.teb_base = teb;
575 info->pthread_info.teb_sel = thread_data->fs;
577 /* inherit debug registers from parent thread */
578 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
579 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
580 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
581 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
582 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
583 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
585 if (!stack_reserve || !stack_commit)
587 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
588 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
589 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
591 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
592 stack_reserve += page_size; /* for the guard page */
593 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
594 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
596 info->pthread_info.stack_base = NULL;
597 info->pthread_info.stack_size = stack_reserve;
598 info->pthread_info.entry = start_thread;
599 info->entry_point = start;
600 info->entry_arg = param;
602 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
604 status = STATUS_NO_MEMORY;
607 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
609 if (id) id->UniqueThread = ULongToHandle(tid);
610 if (handle_ptr) *handle_ptr = handle;
611 else NtClose( handle );
613 return STATUS_SUCCESS;
616 if (thread_data) wine_ldt_free_fs( thread_data->fs );
620 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
622 if (handle) NtClose( handle );
623 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
624 close( request_pipe[1] );
629 /***********************************************************************
630 * RtlExitUserThread (NTDLL.@)
632 void WINAPI RtlExitUserThread( ULONG status )
635 server_exit_thread( status );
639 /***********************************************************************
640 * NtOpenThread (NTDLL.@)
641 * ZwOpenThread (NTDLL.@)
643 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
644 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
648 SERVER_START_REQ( open_thread )
650 req->tid = HandleToULong(id->UniqueThread);
651 req->access = access;
652 req->attributes = attr ? attr->Attributes : 0;
653 ret = wine_server_call( req );
654 *handle = reply->handle;
661 /******************************************************************************
662 * NtSuspendThread (NTDLL.@)
663 * ZwSuspendThread (NTDLL.@)
665 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
669 SERVER_START_REQ( suspend_thread )
671 req->handle = handle;
672 if (!(ret = wine_server_call( req ))) *count = reply->count;
679 /******************************************************************************
680 * NtResumeThread (NTDLL.@)
681 * ZwResumeThread (NTDLL.@)
683 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
687 SERVER_START_REQ( resume_thread )
689 req->handle = handle;
690 if (!(ret = wine_server_call( req ))) *count = reply->count;
697 /******************************************************************************
698 * NtAlertResumeThread (NTDLL.@)
699 * ZwAlertResumeThread (NTDLL.@)
701 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
703 FIXME( "stub: should alert thread %p\n", handle );
704 return NtResumeThread( handle, count );
708 /******************************************************************************
709 * NtAlertThread (NTDLL.@)
710 * ZwAlertThread (NTDLL.@)
712 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
714 FIXME( "stub: %p\n", handle );
715 return STATUS_NOT_IMPLEMENTED;
719 /******************************************************************************
720 * NtTerminateThread (NTDLL.@)
721 * ZwTerminateThread (NTDLL.@)
723 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
728 SERVER_START_REQ( terminate_thread )
730 req->handle = handle;
731 req->exit_code = exit_code;
732 ret = wine_server_call( req );
733 self = !ret && reply->self;
740 if (last) exit( exit_code );
741 else server_abort_thread( exit_code );
747 /******************************************************************************
748 * NtQueueApcThread (NTDLL.@)
750 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
751 ULONG_PTR arg2, ULONG_PTR arg3 )
754 SERVER_START_REQ( queue_apc )
756 req->thread = handle;
759 req->call.type = APC_USER;
760 req->call.user.func = func;
761 req->call.user.args[0] = arg1;
762 req->call.user.args[1] = arg2;
763 req->call.user.args[2] = arg3;
765 else req->call.type = APC_NONE; /* wake up only */
766 ret = wine_server_call( req );
773 /***********************************************************************
774 * NtSetContextThread (NTDLL.@)
775 * ZwSetContextThread (NTDLL.@)
777 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
784 /* on i386 debug registers always require a server call */
785 self = (handle == GetCurrentThread());
786 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
788 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
789 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
790 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
791 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
797 SERVER_START_REQ( set_thread_context )
799 req->handle = handle;
800 req->flags = context->ContextFlags;
802 wine_server_add_data( req, context, sizeof(*context) );
803 ret = wine_server_call( req );
808 if (ret == STATUS_PENDING)
810 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
812 for (i = 0; i < 100; i++)
814 SERVER_START_REQ( set_thread_context )
816 req->handle = handle;
817 req->flags = context->ContextFlags;
819 wine_server_add_data( req, context, sizeof(*context) );
820 ret = wine_server_call( req );
823 if (ret != STATUS_PENDING) break;
826 NtResumeThread( handle, &dummy );
828 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
834 if (self) set_cpu_context( context );
835 return STATUS_SUCCESS;
839 /* copy a context structure according to the flags */
840 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
843 flags &= ~CONTEXT_i386; /* get rid of CPU id */
844 if (flags & CONTEXT_INTEGER)
853 if (flags & CONTEXT_CONTROL)
858 to->SegCs = from->SegCs;
859 to->SegSs = from->SegSs;
860 to->EFlags = from->EFlags;
862 if (flags & CONTEXT_SEGMENTS)
864 to->SegDs = from->SegDs;
865 to->SegEs = from->SegEs;
866 to->SegFs = from->SegFs;
867 to->SegGs = from->SegGs;
869 if (flags & CONTEXT_DEBUG_REGISTERS)
878 if (flags & CONTEXT_FLOATING_POINT)
880 to->FloatSave = from->FloatSave;
882 #elif defined(__x86_64__)
883 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
884 if (flags & CONTEXT_CONTROL)
889 to->SegCs = from->SegCs;
890 to->SegSs = from->SegSs;
891 to->EFlags = from->EFlags;
892 to->MxCsr = from->MxCsr;
894 if (flags & CONTEXT_INTEGER)
911 if (flags & CONTEXT_SEGMENTS)
913 to->SegDs = from->SegDs;
914 to->SegEs = from->SegEs;
915 to->SegFs = from->SegFs;
916 to->SegGs = from->SegGs;
918 if (flags & CONTEXT_FLOATING_POINT)
920 to->u.FltSave = from->u.FltSave;
922 if (flags & CONTEXT_DEBUG_REGISTERS)
931 #elif defined(__sparc__)
932 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
933 if (flags & CONTEXT_CONTROL)
942 if (flags & CONTEXT_INTEGER)
977 if (flags & CONTEXT_FLOATING_POINT)
981 #elif defined(__powerpc__)
983 if (flags & CONTEXT_CONTROL)
989 if (flags & CONTEXT_INTEGER)
991 to->Gpr0 = from->Gpr0;
992 to->Gpr1 = from->Gpr1;
993 to->Gpr2 = from->Gpr2;
994 to->Gpr3 = from->Gpr3;
995 to->Gpr4 = from->Gpr4;
996 to->Gpr5 = from->Gpr5;
997 to->Gpr6 = from->Gpr6;
998 to->Gpr7 = from->Gpr7;
999 to->Gpr8 = from->Gpr8;
1000 to->Gpr9 = from->Gpr9;
1001 to->Gpr10 = from->Gpr10;
1002 to->Gpr11 = from->Gpr11;
1003 to->Gpr12 = from->Gpr12;
1004 to->Gpr13 = from->Gpr13;
1005 to->Gpr14 = from->Gpr14;
1006 to->Gpr15 = from->Gpr15;
1007 to->Gpr16 = from->Gpr16;
1008 to->Gpr17 = from->Gpr17;
1009 to->Gpr18 = from->Gpr18;
1010 to->Gpr19 = from->Gpr19;
1011 to->Gpr20 = from->Gpr20;
1012 to->Gpr21 = from->Gpr21;
1013 to->Gpr22 = from->Gpr22;
1014 to->Gpr23 = from->Gpr23;
1015 to->Gpr24 = from->Gpr24;
1016 to->Gpr25 = from->Gpr25;
1017 to->Gpr26 = from->Gpr26;
1018 to->Gpr27 = from->Gpr27;
1019 to->Gpr28 = from->Gpr28;
1020 to->Gpr29 = from->Gpr29;
1021 to->Gpr30 = from->Gpr30;
1022 to->Gpr31 = from->Gpr31;
1023 to->Xer = from->Xer;
1026 if (flags & CONTEXT_FLOATING_POINT)
1028 to->Fpr0 = from->Fpr0;
1029 to->Fpr1 = from->Fpr1;
1030 to->Fpr2 = from->Fpr2;
1031 to->Fpr3 = from->Fpr3;
1032 to->Fpr4 = from->Fpr4;
1033 to->Fpr5 = from->Fpr5;
1034 to->Fpr6 = from->Fpr6;
1035 to->Fpr7 = from->Fpr7;
1036 to->Fpr8 = from->Fpr8;
1037 to->Fpr9 = from->Fpr9;
1038 to->Fpr10 = from->Fpr10;
1039 to->Fpr11 = from->Fpr11;
1040 to->Fpr12 = from->Fpr12;
1041 to->Fpr13 = from->Fpr13;
1042 to->Fpr14 = from->Fpr14;
1043 to->Fpr15 = from->Fpr15;
1044 to->Fpr16 = from->Fpr16;
1045 to->Fpr17 = from->Fpr17;
1046 to->Fpr18 = from->Fpr18;
1047 to->Fpr19 = from->Fpr19;
1048 to->Fpr20 = from->Fpr20;
1049 to->Fpr21 = from->Fpr21;
1050 to->Fpr22 = from->Fpr22;
1051 to->Fpr23 = from->Fpr23;
1052 to->Fpr24 = from->Fpr24;
1053 to->Fpr25 = from->Fpr25;
1054 to->Fpr26 = from->Fpr26;
1055 to->Fpr27 = from->Fpr27;
1056 to->Fpr28 = from->Fpr28;
1057 to->Fpr29 = from->Fpr29;
1058 to->Fpr30 = from->Fpr30;
1059 to->Fpr31 = from->Fpr31;
1060 to->Fpscr = from->Fpscr;
1063 #error You must implement context copying for your CPU
1068 /***********************************************************************
1069 * NtGetContextThread (NTDLL.@)
1070 * ZwGetContextThread (NTDLL.@)
1072 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1077 DWORD needed_flags = context->ContextFlags;
1078 BOOL self = (handle == GetCurrentThread());
1081 /* on i386 debug registers always require a server call */
1082 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1087 SERVER_START_REQ( get_thread_context )
1089 req->handle = handle;
1090 req->flags = context->ContextFlags;
1092 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1093 ret = wine_server_call( req );
1098 if (ret == STATUS_PENDING)
1100 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1102 for (i = 0; i < 100; i++)
1104 SERVER_START_REQ( get_thread_context )
1106 req->handle = handle;
1107 req->flags = context->ContextFlags;
1109 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1110 ret = wine_server_call( req );
1113 if (ret != STATUS_PENDING) break;
1116 NtResumeThread( handle, &dummy );
1118 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1120 if (ret) return ret;
1121 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1122 needed_flags &= ~ctx.ContextFlags;
1129 get_cpu_context( &ctx );
1130 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1133 /* update the cached version of the debug registers */
1134 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1136 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1137 regs->dr0 = context->Dr0;
1138 regs->dr1 = context->Dr1;
1139 regs->dr2 = context->Dr2;
1140 regs->dr3 = context->Dr3;
1141 regs->dr6 = context->Dr6;
1142 regs->dr7 = context->Dr7;
1146 return STATUS_SUCCESS;
1150 /******************************************************************************
1151 * NtQueryInformationThread (NTDLL.@)
1152 * ZwQueryInformationThread (NTDLL.@)
1154 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1155 void *data, ULONG length, ULONG *ret_len )
1161 case ThreadBasicInformation:
1163 THREAD_BASIC_INFORMATION info;
1165 SERVER_START_REQ( get_thread_info )
1167 req->handle = handle;
1169 if (!(status = wine_server_call( req )))
1171 info.ExitStatus = reply->exit_code;
1172 info.TebBaseAddress = reply->teb;
1173 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
1174 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
1175 info.AffinityMask = reply->affinity;
1176 info.Priority = reply->priority;
1177 info.BasePriority = reply->priority; /* FIXME */
1181 if (status == STATUS_SUCCESS)
1183 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1184 if (ret_len) *ret_len = min( length, sizeof(info) );
1190 KERNEL_USER_TIMES kusrt;
1191 /* We need to do a server call to get the creation time or exit time */
1192 /* This works on any thread */
1193 SERVER_START_REQ( get_thread_info )
1195 req->handle = handle;
1197 status = wine_server_call( req );
1198 if (status == STATUS_SUCCESS)
1200 kusrt.CreateTime.QuadPart = reply->creation_time;
1201 kusrt.ExitTime.QuadPart = reply->exit_time;
1205 if (status == STATUS_SUCCESS)
1207 /* We call times(2) for kernel time or user time */
1208 /* We can only (portably) do this for the current thread */
1209 if (handle == GetCurrentThread())
1211 struct tms time_buf;
1212 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1215 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1216 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1220 kusrt.KernelTime.QuadPart = 0;
1221 kusrt.UserTime.QuadPart = 0;
1222 FIXME("Cannot get kerneltime or usertime of other threads\n");
1224 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1225 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1229 case ThreadDescriptorTableEntry:
1232 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1233 if (length < sizeof(*tdi))
1234 status = STATUS_INFO_LENGTH_MISMATCH;
1235 else if (!(tdi->Selector & 4)) /* GDT selector */
1237 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1238 status = STATUS_SUCCESS;
1239 if (!sel) /* null selector */
1240 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1243 tdi->Entry.BaseLow = 0;
1244 tdi->Entry.HighWord.Bits.BaseMid = 0;
1245 tdi->Entry.HighWord.Bits.BaseHi = 0;
1246 tdi->Entry.LimitLow = 0xffff;
1247 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1248 tdi->Entry.HighWord.Bits.Dpl = 3;
1249 tdi->Entry.HighWord.Bits.Sys = 0;
1250 tdi->Entry.HighWord.Bits.Pres = 1;
1251 tdi->Entry.HighWord.Bits.Granularity = 1;
1252 tdi->Entry.HighWord.Bits.Default_Big = 1;
1253 tdi->Entry.HighWord.Bits.Type = 0x12;
1254 /* it has to be one of the system GDT selectors */
1255 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1257 if (sel == (wine_get_cs() & ~3))
1258 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1259 else status = STATUS_ACCESS_DENIED;
1265 SERVER_START_REQ( get_selector_entry )
1267 req->handle = handle;
1268 req->entry = tdi->Selector >> 3;
1269 status = wine_server_call( req );
1272 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1273 status = STATUS_ACCESS_VIOLATION;
1276 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1277 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1278 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1284 if (status == STATUS_SUCCESS && ret_len)
1285 /* yes, that's a bit strange, but it's the way it is */
1286 *ret_len = sizeof(LDT_ENTRY);
1288 status = STATUS_NOT_IMPLEMENTED;
1292 case ThreadAmILastThread:
1294 SERVER_START_REQ(get_thread_info)
1296 req->handle = handle;
1298 status = wine_server_call( req );
1299 if (status == STATUS_SUCCESS)
1301 BOOLEAN last = reply->last;
1302 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1303 if (ret_len) *ret_len = min( length, sizeof(last) );
1309 case ThreadPriority:
1310 case ThreadBasePriority:
1311 case ThreadAffinityMask:
1312 case ThreadImpersonationToken:
1313 case ThreadEnableAlignmentFaultFixup:
1314 case ThreadEventPair_Reusable:
1315 case ThreadQuerySetWin32StartAddress:
1316 case ThreadZeroTlsCell:
1317 case ThreadPerformanceCount:
1318 case ThreadIdealProcessor:
1319 case ThreadPriorityBoost:
1320 case ThreadSetTlsArrayAddress:
1321 case ThreadIsIoPending:
1323 FIXME( "info class %d not supported yet\n", class );
1324 return STATUS_NOT_IMPLEMENTED;
1329 /******************************************************************************
1330 * NtSetInformationThread (NTDLL.@)
1331 * ZwSetInformationThread (NTDLL.@)
1333 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1334 LPCVOID data, ULONG length )
1339 case ThreadZeroTlsCell:
1340 if (handle == GetCurrentThread())
1345 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1346 index = *(const DWORD *)data;
1347 if (index < TLS_MINIMUM_AVAILABLE)
1349 RtlAcquirePebLock();
1350 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1352 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1353 teb->TlsSlots[index] = 0;
1355 RtlReleasePebLock();
1359 index -= TLS_MINIMUM_AVAILABLE;
1360 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1361 return STATUS_INVALID_PARAMETER;
1362 RtlAcquirePebLock();
1363 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1365 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1366 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1368 RtlReleasePebLock();
1370 return STATUS_SUCCESS;
1372 FIXME( "ZeroTlsCell not supported on other threads\n" );
1373 return STATUS_NOT_IMPLEMENTED;
1375 case ThreadImpersonationToken:
1377 const HANDLE *phToken = data;
1378 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1379 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1380 SERVER_START_REQ( set_thread_info )
1382 req->handle = handle;
1383 req->token = *phToken;
1384 req->mask = SET_THREAD_INFO_TOKEN;
1385 status = wine_server_call( req );
1390 case ThreadBasePriority:
1392 const DWORD *pprio = data;
1393 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1394 SERVER_START_REQ( set_thread_info )
1396 req->handle = handle;
1397 req->priority = *pprio;
1398 req->mask = SET_THREAD_INFO_PRIORITY;
1399 status = wine_server_call( req );
1404 case ThreadAffinityMask:
1406 const DWORD *paff = data;
1407 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1408 SERVER_START_REQ( set_thread_info )
1410 req->handle = handle;
1411 req->affinity = *paff;
1412 req->mask = SET_THREAD_INFO_AFFINITY;
1413 status = wine_server_call( req );
1418 case ThreadBasicInformation:
1420 case ThreadPriority:
1421 case ThreadDescriptorTableEntry:
1422 case ThreadEnableAlignmentFaultFixup:
1423 case ThreadEventPair_Reusable:
1424 case ThreadQuerySetWin32StartAddress:
1425 case ThreadPerformanceCount:
1426 case ThreadAmILastThread:
1427 case ThreadIdealProcessor:
1428 case ThreadPriorityBoost:
1429 case ThreadSetTlsArrayAddress:
1430 case ThreadIsIoPending:
1432 FIXME( "info class %d not supported yet\n", class );
1433 return STATUS_NOT_IMPLEMENTED;
1438 /**********************************************************************
1439 * NtCurrentTeb (NTDLL.@)
1441 #if defined(__i386__) && defined(__GNUC__)
1443 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1445 #elif defined(__i386__) && defined(_MSC_VER)
1447 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1451 /**********************************************************************/
1453 TEB * WINAPI NtCurrentTeb(void)
1455 return pthread_functions.get_current_teb();
1458 #endif /* __i386__ */