push 955563f995be8b0942dbb757ceb5b3a4c8ccafbf
[wine/hacks.git] / dlls / ntdll / thread.c
blob0b924b2cf7e3b9f12d34346416f5dd128661f9f9
1 /*
2 * NT threads support
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <stdarg.h>
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
32 #endif
34 #define NONAMELESSUNION
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "winternl.h"
38 #include "wine/library.h"
39 #include "wine/server.h"
40 #include "wine/debug.h"
41 #include "ntdll_misc.h"
42 #include "ddk/wdm.h"
43 #include "wine/exception.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(thread);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
48 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
50 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
52 /* info passed to a starting thread */
53 struct startup_info
55 TEB *teb;
56 PRTL_THREAD_START_ROUTINE entry_point;
57 void *entry_arg;
60 static PEB_LDR_DATA ldr;
61 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
62 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
63 static RTL_BITMAP tls_bitmap;
64 static RTL_BITMAP tls_expansion_bitmap;
65 static RTL_BITMAP fls_bitmap;
66 static LIST_ENTRY tls_links;
67 static size_t sigstack_total_size;
68 static ULONG sigstack_zero_bits;
69 static int nb_threads = 1;
71 static RTL_CRITICAL_SECTION ldt_section;
72 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
74 0, 0, &ldt_section,
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)
86 sigset_t sigset;
88 pthread_sigmask( 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_sigmask( SIG_SETMASK, &sigset, NULL );
101 else RtlLeaveCriticalSection( &ldt_section );
105 /***********************************************************************
106 * init_teb
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 /***********************************************************************
129 * fix_unicode_string
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;
138 str->Buffer = NULL;
139 return;
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);
149 else
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 )
162 void *ptr;
163 SIZE_T env_size;
164 NTSTATUS status;
165 RTL_USER_PROCESS_PARAMETERS *params = NULL;
167 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 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 = wine_server_ptr_handle( reply->exe_file );
181 params->hStdInput = wine_server_ptr_handle( reply->hstdin );
182 params->hStdOutput = wine_server_ptr_handle( reply->hstdout );
183 params->hStdError = wine_server_ptr_handle( reply->hstderr );
186 SERVER_END_REQ;
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( &params->CurrentDirectory.DosPath, (char *)info_size );
193 fix_unicode_string( &params->DllPath, (char *)info_size );
194 fix_unicode_string( &params->ImagePathName, (char *)info_size );
195 fix_unicode_string( &params->CommandLine, (char *)info_size );
196 fix_unicode_string( &params->WindowTitle, (char *)info_size );
197 fix_unicode_string( &params->Desktop, (char *)info_size );
198 fix_unicode_string( &params->ShellInfo, (char *)info_size );
199 fix_unicode_string( &params->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;
204 ptr = NULL;
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 );
212 return status;
216 /***********************************************************************
217 * thread_init
219 * Setup the initial thread.
221 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
223 HANDLE thread_init(void)
225 PEB *peb;
226 TEB *teb;
227 void *addr;
228 SIZE_T size, info_size;
229 HANDLE exe_file = 0;
230 LARGE_INTEGER now;
231 struct ntdll_thread_data *thread_data;
232 static struct debug_info debug_info; /* debug info for initial thread */
234 virtual_init();
236 /* reserve space for shared user data */
238 addr = (void *)0x7ffe0000;
239 size = 0x10000;
240 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
241 user_shared_data = addr;
243 /* allocate and initialize the PEB */
245 addr = NULL;
246 size = sizeof(*peb);
247 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
248 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
249 peb = addr;
251 peb->NumberOfProcessors = 1;
252 peb->ProcessParameters = &params;
253 peb->TlsBitmap = &tls_bitmap;
254 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
255 peb->FlsBitmap = &fls_bitmap;
256 peb->LdrData = &ldr;
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 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
264 InitializeListHead( &peb->FlsListHead );
265 InitializeListHead( &ldr.InLoadOrderModuleList );
266 InitializeListHead( &ldr.InMemoryOrderModuleList );
267 InitializeListHead( &ldr.InInitializationOrderModuleList );
268 InitializeListHead( &tls_links );
270 /* allocate and initialize the initial TEB */
272 sigstack_total_size = get_signal_stack_total_size();
273 while (1U << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
274 assert( 1U << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
275 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
277 addr = NULL;
278 size = sigstack_total_size;
279 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
280 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
281 teb = addr;
282 teb->Peb = peb;
283 init_teb( teb );
284 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
285 thread_data->debug_info = &debug_info;
286 InsertHeadList( &tls_links, &teb->TlsLinks );
288 signal_init_thread( teb );
289 virtual_init_threading();
291 debug_info.str_pos = debug_info.strings;
292 debug_info.out_pos = debug_info.output;
293 debug_init();
295 /* setup the server connection */
296 server_init_process();
297 info_size = server_init_thread( peb );
299 /* create the process heap */
300 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
302 MESSAGE( "wine: failed to create the process heap\n" );
303 exit(1);
306 /* allocate user parameters */
307 if (info_size)
309 init_user_process_params( info_size, &exe_file );
311 else
313 /* This is wine specific: we have no parent (we're started from unix)
314 * so, create a simple console with bare handles to unix stdio
316 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, &params.hStdInput );
317 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
318 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
321 /* initialize LDT locking */
322 wine_ldt_init_locking( ldt_lock, ldt_unlock );
324 /* initialize time values in user_shared_data */
325 NtQuerySystemTime( &now );
326 user_shared_data->SystemTime.LowPart = now.u.LowPart;
327 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
328 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
329 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
330 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
331 user_shared_data->TickCountMultiplier = 1 << 24;
333 return exe_file;
337 /***********************************************************************
338 * abort_thread
340 void abort_thread( int status )
342 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
343 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
345 close( ntdll_get_thread_data()->wait_fd[0] );
346 close( ntdll_get_thread_data()->wait_fd[1] );
347 close( ntdll_get_thread_data()->reply_fd );
348 close( ntdll_get_thread_data()->request_fd );
349 pthread_exit( UIntToPtr(status) );
353 /***********************************************************************
354 * exit_thread
356 void exit_thread( int status )
358 static void *prev_teb;
359 TEB *teb;
361 if (status) /* send the exit code to the server (0 is already the default) */
363 SERVER_START_REQ( terminate_thread )
365 req->handle = wine_server_obj_handle( GetCurrentThread() );
366 req->exit_code = status;
367 wine_server_call( req );
369 SERVER_END_REQ;
372 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
374 LdrShutdownProcess();
375 exit( status );
378 LdrShutdownThread();
379 RtlAcquirePebLock();
380 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
381 RtlReleasePebLock();
382 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
383 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
385 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
387 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
389 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
390 SIZE_T size;
392 pthread_join( thread_data->pthread_id, NULL );
393 wine_ldt_free_fs( thread_data->fs );
394 size = 0;
395 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
396 size = 0;
397 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
400 close( ntdll_get_thread_data()->wait_fd[0] );
401 close( ntdll_get_thread_data()->wait_fd[1] );
402 close( ntdll_get_thread_data()->reply_fd );
403 close( ntdll_get_thread_data()->request_fd );
404 pthread_exit( UIntToPtr(status) );
408 /***********************************************************************
409 * start_thread
411 * Startup routine for a newly created thread.
413 static void start_thread( struct startup_info *info )
415 TEB *teb = info->teb;
416 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
417 PRTL_THREAD_START_ROUTINE func = info->entry_point;
418 void *arg = info->entry_arg;
419 struct debug_info debug_info;
421 debug_info.str_pos = debug_info.strings;
422 debug_info.out_pos = debug_info.output;
423 thread_data->debug_info = &debug_info;
424 thread_data->pthread_id = pthread_self();
426 signal_init_thread( teb );
427 server_init_thread( func );
428 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
430 RtlAcquirePebLock();
431 InsertHeadList( &tls_links, &teb->TlsLinks );
432 RtlReleasePebLock();
434 MODULE_DllThreadAttach( NULL );
436 if (TRACE_ON(relay))
437 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
439 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
443 /***********************************************************************
444 * RtlCreateUserThread (NTDLL.@)
446 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
447 BOOLEAN suspended, PVOID stack_addr,
448 SIZE_T stack_reserve, SIZE_T stack_commit,
449 PRTL_THREAD_START_ROUTINE start, void *param,
450 HANDLE *handle_ptr, CLIENT_ID *id )
452 sigset_t sigset;
453 pthread_t pthread_id;
454 pthread_attr_t attr;
455 struct ntdll_thread_data *thread_data = NULL;
456 struct ntdll_thread_regs *thread_regs;
457 struct startup_info *info = NULL;
458 void *addr = NULL;
459 HANDLE handle = 0;
460 TEB *teb;
461 DWORD tid = 0;
462 int request_pipe[2];
463 NTSTATUS status;
464 SIZE_T size;
466 if (process != NtCurrentProcess())
468 apc_call_t call;
469 apc_result_t result;
471 memset( &call, 0, sizeof(call) );
473 call.create_thread.type = APC_CREATE_THREAD;
474 call.create_thread.func = wine_server_client_ptr( start );
475 call.create_thread.arg = wine_server_client_ptr( param );
476 call.create_thread.reserve = stack_reserve;
477 call.create_thread.commit = stack_commit;
478 call.create_thread.suspend = suspended;
479 status = NTDLL_queue_process_apc( process, &call, &result );
480 if (status != STATUS_SUCCESS) return status;
482 if (result.create_thread.status == STATUS_SUCCESS)
484 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
485 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
486 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
488 return result.create_thread.status;
491 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
492 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
493 wine_server_send_fd( request_pipe[0] );
495 SERVER_START_REQ( new_thread )
497 req->access = THREAD_ALL_ACCESS;
498 req->attributes = 0; /* FIXME */
499 req->suspend = suspended;
500 req->request_fd = request_pipe[0];
501 if (!(status = wine_server_call( req )))
503 handle = wine_server_ptr_handle( reply->handle );
504 tid = reply->tid;
506 close( request_pipe[0] );
508 SERVER_END_REQ;
510 if (status)
512 close( request_pipe[1] );
513 return status;
516 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
518 addr = NULL;
519 size = sigstack_total_size;
520 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
521 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
522 goto error;
523 teb = addr;
524 teb->Peb = NtCurrentTeb()->Peb;
525 info = (struct startup_info *)(teb + 1);
526 info->teb = teb;
527 info->entry_point = start;
528 info->entry_arg = param;
530 if ((status = init_teb( teb ))) goto error;
532 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
533 teb->ClientId.UniqueThread = ULongToHandle(tid);
535 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
536 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
537 thread_data->request_fd = request_pipe[1];
539 /* inherit debug registers from parent thread */
540 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
541 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
542 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
543 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
544 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
545 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
547 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
549 pthread_attr_init( &attr );
550 pthread_attr_setstack( &attr, teb->DeallocationStack,
551 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
552 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
553 interlocked_xchg_add( &nb_threads, 1 );
554 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
556 interlocked_xchg_add( &nb_threads, -1 );
557 pthread_attr_destroy( &attr );
558 size = 0;
559 NtFreeVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
560 status = STATUS_NO_MEMORY;
561 goto error;
563 pthread_attr_destroy( &attr );
564 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
566 if (id) id->UniqueThread = ULongToHandle(tid);
567 if (handle_ptr) *handle_ptr = handle;
568 else NtClose( handle );
570 return STATUS_SUCCESS;
572 error:
573 if (thread_data) wine_ldt_free_fs( thread_data->fs );
574 if (addr)
576 size = 0;
577 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
579 if (handle) NtClose( handle );
580 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
581 close( request_pipe[1] );
582 return status;
586 /***********************************************************************
587 * NtOpenThread (NTDLL.@)
588 * ZwOpenThread (NTDLL.@)
590 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
591 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
593 NTSTATUS ret;
595 SERVER_START_REQ( open_thread )
597 req->tid = HandleToULong(id->UniqueThread);
598 req->access = access;
599 req->attributes = attr ? attr->Attributes : 0;
600 ret = wine_server_call( req );
601 *handle = wine_server_ptr_handle( reply->handle );
603 SERVER_END_REQ;
604 return ret;
608 /******************************************************************************
609 * NtSuspendThread (NTDLL.@)
610 * ZwSuspendThread (NTDLL.@)
612 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
614 NTSTATUS ret;
616 SERVER_START_REQ( suspend_thread )
618 req->handle = wine_server_obj_handle( handle );
619 if (!(ret = wine_server_call( req ))) *count = reply->count;
621 SERVER_END_REQ;
622 return ret;
626 /******************************************************************************
627 * NtResumeThread (NTDLL.@)
628 * ZwResumeThread (NTDLL.@)
630 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
632 NTSTATUS ret;
634 SERVER_START_REQ( resume_thread )
636 req->handle = wine_server_obj_handle( handle );
637 if (!(ret = wine_server_call( req ))) *count = reply->count;
639 SERVER_END_REQ;
640 return ret;
644 /******************************************************************************
645 * NtAlertResumeThread (NTDLL.@)
646 * ZwAlertResumeThread (NTDLL.@)
648 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
650 FIXME( "stub: should alert thread %p\n", handle );
651 return NtResumeThread( handle, count );
655 /******************************************************************************
656 * NtAlertThread (NTDLL.@)
657 * ZwAlertThread (NTDLL.@)
659 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
661 FIXME( "stub: %p\n", handle );
662 return STATUS_NOT_IMPLEMENTED;
666 /******************************************************************************
667 * NtTerminateThread (NTDLL.@)
668 * ZwTerminateThread (NTDLL.@)
670 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
672 NTSTATUS ret;
673 BOOL self, last;
675 SERVER_START_REQ( terminate_thread )
677 req->handle = wine_server_obj_handle( handle );
678 req->exit_code = exit_code;
679 ret = wine_server_call( req );
680 self = !ret && reply->self;
681 last = reply->last;
683 SERVER_END_REQ;
685 if (self)
687 if (last) _exit( exit_code );
688 else abort_thread( exit_code );
690 return ret;
694 /******************************************************************************
695 * NtQueueApcThread (NTDLL.@)
697 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
698 ULONG_PTR arg2, ULONG_PTR arg3 )
700 NTSTATUS ret;
701 SERVER_START_REQ( queue_apc )
703 req->handle = wine_server_obj_handle( handle );
704 if (func)
706 req->call.type = APC_USER;
707 req->call.user.func = wine_server_client_ptr( func );
708 req->call.user.args[0] = arg1;
709 req->call.user.args[1] = arg2;
710 req->call.user.args[2] = arg3;
712 else req->call.type = APC_NONE; /* wake up only */
713 ret = wine_server_call( req );
715 SERVER_END_REQ;
716 return ret;
720 /***********************************************************************
721 * NtSetContextThread (NTDLL.@)
722 * ZwSetContextThread (NTDLL.@)
724 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
726 NTSTATUS ret;
727 DWORD dummy, i;
728 BOOL self = FALSE;
730 #ifdef __i386__
731 /* on i386 debug registers always require a server call */
732 self = (handle == GetCurrentThread());
733 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
735 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
736 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
737 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
738 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
740 #endif
742 if (!self)
744 context_t server_context;
746 context_to_server( &server_context, context );
748 SERVER_START_REQ( set_thread_context )
750 req->handle = wine_server_obj_handle( handle );
751 req->suspend = 0;
752 wine_server_add_data( req, &server_context, sizeof(server_context) );
753 ret = wine_server_call( req );
754 self = reply->self;
756 SERVER_END_REQ;
758 if (ret == STATUS_PENDING)
760 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
762 for (i = 0; i < 100; i++)
764 SERVER_START_REQ( set_thread_context )
766 req->handle = wine_server_obj_handle( handle );
767 req->suspend = 0;
768 wine_server_add_data( req, &server_context, sizeof(server_context) );
769 ret = wine_server_call( req );
771 SERVER_END_REQ;
772 if (ret == STATUS_PENDING)
774 LARGE_INTEGER timeout;
775 timeout.QuadPart = -10000;
776 NtDelayExecution( FALSE, &timeout );
778 else break;
780 NtResumeThread( handle, &dummy );
782 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
785 if (ret) return ret;
788 if (self) set_cpu_context( context );
789 return STATUS_SUCCESS;
793 /* convert CPU-specific flags to generic server flags */
794 static inline unsigned int get_server_context_flags( DWORD flags )
796 unsigned int ret = 0;
798 flags &= ~0x3f; /* mask CPU id flags */
799 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
800 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
801 #ifdef CONTEXT_SEGMENTS
802 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
803 #endif
804 #ifdef CONTEXT_FLOATING_POINT
805 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
806 #endif
807 #ifdef CONTEXT_DEBUG_REGISTERS
808 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
809 #endif
810 #ifdef CONTEXT_EXTENDED_REGISTERS
811 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
812 #endif
813 return ret;
816 /***********************************************************************
817 * NtGetContextThread (NTDLL.@)
818 * ZwGetContextThread (NTDLL.@)
820 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
822 NTSTATUS ret;
823 DWORD dummy, i;
824 DWORD needed_flags = context->ContextFlags;
825 BOOL self = (handle == GetCurrentThread());
827 #ifdef __i386__
828 /* on i386 debug registers always require a server call */
829 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
830 #endif
832 if (!self)
834 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
835 context_t server_context;
837 SERVER_START_REQ( get_thread_context )
839 req->handle = wine_server_obj_handle( handle );
840 req->flags = server_flags;
841 req->suspend = 0;
842 wine_server_set_reply( req, &server_context, sizeof(server_context) );
843 ret = wine_server_call( req );
844 self = reply->self;
846 SERVER_END_REQ;
848 if (ret == STATUS_PENDING)
850 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
852 for (i = 0; i < 100; i++)
854 SERVER_START_REQ( get_thread_context )
856 req->handle = wine_server_obj_handle( handle );
857 req->flags = server_flags;
858 req->suspend = 0;
859 wine_server_set_reply( req, &server_context, sizeof(server_context) );
860 ret = wine_server_call( req );
862 SERVER_END_REQ;
863 if (ret == STATUS_PENDING)
865 LARGE_INTEGER timeout;
866 timeout.QuadPart = -10000;
867 NtDelayExecution( FALSE, &timeout );
869 else break;
871 NtResumeThread( handle, &dummy );
873 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
875 if (!ret) ret = context_from_server( context, &server_context );
876 if (ret) return ret;
877 needed_flags &= ~context->ContextFlags;
880 if (self)
882 if (needed_flags)
884 CONTEXT ctx;
885 RtlCaptureContext( &ctx );
886 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
887 context->ContextFlags |= ctx.ContextFlags & needed_flags;
889 #ifdef __i386__
890 /* update the cached version of the debug registers */
891 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
893 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
894 regs->dr0 = context->Dr0;
895 regs->dr1 = context->Dr1;
896 regs->dr2 = context->Dr2;
897 regs->dr3 = context->Dr3;
898 regs->dr6 = context->Dr6;
899 regs->dr7 = context->Dr7;
901 #endif
903 return STATUS_SUCCESS;
907 /******************************************************************************
908 * NtQueryInformationThread (NTDLL.@)
909 * ZwQueryInformationThread (NTDLL.@)
911 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
912 void *data, ULONG length, ULONG *ret_len )
914 NTSTATUS status;
916 switch(class)
918 case ThreadBasicInformation:
920 THREAD_BASIC_INFORMATION info;
921 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
923 SERVER_START_REQ( get_thread_info )
925 req->handle = wine_server_obj_handle( handle );
926 req->tid_in = 0;
927 if (!(status = wine_server_call( req )))
929 info.ExitStatus = reply->exit_code;
930 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
931 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
932 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
933 info.AffinityMask = reply->affinity & affinity_mask;
934 info.Priority = reply->priority;
935 info.BasePriority = reply->priority; /* FIXME */
938 SERVER_END_REQ;
939 if (status == STATUS_SUCCESS)
941 if (data) memcpy( data, &info, min( length, sizeof(info) ));
942 if (ret_len) *ret_len = min( length, sizeof(info) );
945 return status;
946 case ThreadAffinityMask:
948 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
949 ULONG_PTR affinity = 0;
951 SERVER_START_REQ( get_thread_info )
953 req->handle = wine_server_obj_handle( handle );
954 req->tid_in = 0;
955 if (!(status = wine_server_call( req )))
956 affinity = reply->affinity & affinity_mask;
958 SERVER_END_REQ;
959 if (status == STATUS_SUCCESS)
961 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
962 if (ret_len) *ret_len = min( length, sizeof(affinity) );
965 return status;
966 case ThreadTimes:
968 KERNEL_USER_TIMES kusrt;
969 /* We need to do a server call to get the creation time or exit time */
970 /* This works on any thread */
971 SERVER_START_REQ( get_thread_info )
973 req->handle = wine_server_obj_handle( handle );
974 req->tid_in = 0;
975 status = wine_server_call( req );
976 if (status == STATUS_SUCCESS)
978 kusrt.CreateTime.QuadPart = reply->creation_time;
979 kusrt.ExitTime.QuadPart = reply->exit_time;
982 SERVER_END_REQ;
983 if (status == STATUS_SUCCESS)
985 /* We call times(2) for kernel time or user time */
986 /* We can only (portably) do this for the current thread */
987 if (handle == GetCurrentThread())
989 struct tms time_buf;
990 long clocks_per_sec = sysconf(_SC_CLK_TCK);
992 times(&time_buf);
993 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
994 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
996 else
998 static BOOL reported = FALSE;
1000 kusrt.KernelTime.QuadPart = 0;
1001 kusrt.UserTime.QuadPart = 0;
1002 if (reported)
1003 TRACE("Cannot get kerneltime or usertime of other threads\n");
1004 else
1006 FIXME("Cannot get kerneltime or usertime of other threads\n");
1007 reported = TRUE;
1010 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1011 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1014 return status;
1015 case ThreadDescriptorTableEntry:
1017 #ifdef __i386__
1018 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1019 if (length < sizeof(*tdi))
1020 status = STATUS_INFO_LENGTH_MISMATCH;
1021 else if (!(tdi->Selector & 4)) /* GDT selector */
1023 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1024 status = STATUS_SUCCESS;
1025 if (!sel) /* null selector */
1026 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1027 else
1029 tdi->Entry.BaseLow = 0;
1030 tdi->Entry.HighWord.Bits.BaseMid = 0;
1031 tdi->Entry.HighWord.Bits.BaseHi = 0;
1032 tdi->Entry.LimitLow = 0xffff;
1033 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1034 tdi->Entry.HighWord.Bits.Dpl = 3;
1035 tdi->Entry.HighWord.Bits.Sys = 0;
1036 tdi->Entry.HighWord.Bits.Pres = 1;
1037 tdi->Entry.HighWord.Bits.Granularity = 1;
1038 tdi->Entry.HighWord.Bits.Default_Big = 1;
1039 tdi->Entry.HighWord.Bits.Type = 0x12;
1040 /* it has to be one of the system GDT selectors */
1041 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1043 if (sel == (wine_get_cs() & ~3))
1044 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1045 else status = STATUS_ACCESS_DENIED;
1049 else
1051 SERVER_START_REQ( get_selector_entry )
1053 req->handle = wine_server_obj_handle( handle );
1054 req->entry = tdi->Selector >> 3;
1055 status = wine_server_call( req );
1056 if (!status)
1058 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1059 status = STATUS_ACCESS_VIOLATION;
1060 else
1062 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1063 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1064 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1068 SERVER_END_REQ;
1070 if (status == STATUS_SUCCESS && ret_len)
1071 /* yes, that's a bit strange, but it's the way it is */
1072 *ret_len = sizeof(LDT_ENTRY);
1073 #else
1074 status = STATUS_NOT_IMPLEMENTED;
1075 #endif
1076 return status;
1078 case ThreadAmILastThread:
1080 SERVER_START_REQ(get_thread_info)
1082 req->handle = wine_server_obj_handle( handle );
1083 req->tid_in = 0;
1084 status = wine_server_call( req );
1085 if (status == STATUS_SUCCESS)
1087 BOOLEAN last = reply->last;
1088 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1089 if (ret_len) *ret_len = min( length, sizeof(last) );
1092 SERVER_END_REQ;
1093 return status;
1095 case ThreadPriority:
1096 case ThreadBasePriority:
1097 case ThreadImpersonationToken:
1098 case ThreadEnableAlignmentFaultFixup:
1099 case ThreadEventPair_Reusable:
1100 case ThreadQuerySetWin32StartAddress:
1101 case ThreadZeroTlsCell:
1102 case ThreadPerformanceCount:
1103 case ThreadIdealProcessor:
1104 case ThreadPriorityBoost:
1105 case ThreadSetTlsArrayAddress:
1106 case ThreadIsIoPending:
1107 default:
1108 FIXME( "info class %d not supported yet\n", class );
1109 return STATUS_NOT_IMPLEMENTED;
1114 /******************************************************************************
1115 * NtSetInformationThread (NTDLL.@)
1116 * ZwSetInformationThread (NTDLL.@)
1118 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1119 LPCVOID data, ULONG length )
1121 NTSTATUS status;
1122 switch(class)
1124 case ThreadZeroTlsCell:
1125 if (handle == GetCurrentThread())
1127 LIST_ENTRY *entry;
1128 DWORD index;
1130 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1131 index = *(const DWORD *)data;
1132 if (index < TLS_MINIMUM_AVAILABLE)
1134 RtlAcquirePebLock();
1135 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1137 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1138 teb->TlsSlots[index] = 0;
1140 RtlReleasePebLock();
1142 else
1144 index -= TLS_MINIMUM_AVAILABLE;
1145 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1146 return STATUS_INVALID_PARAMETER;
1147 RtlAcquirePebLock();
1148 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1150 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1151 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1153 RtlReleasePebLock();
1155 return STATUS_SUCCESS;
1157 FIXME( "ZeroTlsCell not supported on other threads\n" );
1158 return STATUS_NOT_IMPLEMENTED;
1160 case ThreadImpersonationToken:
1162 const HANDLE *phToken = data;
1163 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1164 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1165 SERVER_START_REQ( set_thread_info )
1167 req->handle = wine_server_obj_handle( handle );
1168 req->token = wine_server_obj_handle( *phToken );
1169 req->mask = SET_THREAD_INFO_TOKEN;
1170 status = wine_server_call( req );
1172 SERVER_END_REQ;
1174 return status;
1175 case ThreadBasePriority:
1177 const DWORD *pprio = data;
1178 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1179 SERVER_START_REQ( set_thread_info )
1181 req->handle = wine_server_obj_handle( handle );
1182 req->priority = *pprio;
1183 req->mask = SET_THREAD_INFO_PRIORITY;
1184 status = wine_server_call( req );
1186 SERVER_END_REQ;
1188 return status;
1189 case ThreadAffinityMask:
1191 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1192 const ULONG_PTR *paff = data;
1193 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1194 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1195 SERVER_START_REQ( set_thread_info )
1197 req->handle = wine_server_obj_handle( handle );
1198 req->affinity = *paff;
1199 req->mask = SET_THREAD_INFO_AFFINITY;
1200 status = wine_server_call( req );
1202 SERVER_END_REQ;
1204 return status;
1205 case ThreadBasicInformation:
1206 case ThreadTimes:
1207 case ThreadPriority:
1208 case ThreadDescriptorTableEntry:
1209 case ThreadEnableAlignmentFaultFixup:
1210 case ThreadEventPair_Reusable:
1211 case ThreadQuerySetWin32StartAddress:
1212 case ThreadPerformanceCount:
1213 case ThreadAmILastThread:
1214 case ThreadIdealProcessor:
1215 case ThreadPriorityBoost:
1216 case ThreadSetTlsArrayAddress:
1217 case ThreadIsIoPending:
1218 default:
1219 FIXME( "info class %d not supported yet\n", class );
1220 return STATUS_NOT_IMPLEMENTED;