dinput: Add missing newline to trace message.
[wine/hacks.git] / dlls / ntdll / thread.c
blob1a5017ebb6ecb6dafd9dbcd351433d2f67647ff9
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 static void DECLSPEC_NORETURN exit_thread( int status )
358 static void *prev_teb;
359 TEB *teb;
361 RtlAcquirePebLock();
362 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
363 RtlReleasePebLock();
364 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
365 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
367 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
368 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) exit( status );
370 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
372 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
373 SIZE_T size;
375 pthread_join( thread_data->pthread_id, NULL );
376 wine_ldt_free_fs( thread_data->fs );
377 size = 0;
378 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
379 size = 0;
380 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
383 close( ntdll_get_thread_data()->wait_fd[0] );
384 close( ntdll_get_thread_data()->wait_fd[1] );
385 close( ntdll_get_thread_data()->reply_fd );
386 close( ntdll_get_thread_data()->request_fd );
387 pthread_exit( UIntToPtr(status) );
391 #ifdef __i386__
392 /* wrapper for apps that don't declare the thread function correctly */
393 extern DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg );
394 __ASM_GLOBAL_FUNC(call_thread_entry_point,
395 "pushl %ebp\n\t"
396 "movl %esp,%ebp\n\t"
397 "subl $4,%esp\n\t"
398 "pushl 12(%ebp)\n\t"
399 "movl 8(%ebp),%eax\n\t"
400 "call *%eax\n\t"
401 "leave\n\t"
402 "ret" )
403 #else
404 static inline DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg )
406 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)entry;
407 return func( arg );
409 #endif
411 /***********************************************************************
412 * call_thread_func
414 * Hack to make things compatible with the thread procedures used by kernel32.CreateThread.
416 static void DECLSPEC_NORETURN call_thread_func( PRTL_THREAD_START_ROUTINE rtl_func, void *arg )
418 DWORD exit_code;
419 BOOL last;
421 MODULE_DllThreadAttach( NULL );
423 if (TRACE_ON(relay))
424 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), rtl_func, arg );
426 exit_code = call_thread_entry_point( rtl_func, arg );
428 /* send the exit code to the server */
429 SERVER_START_REQ( terminate_thread )
431 req->handle = wine_server_obj_handle( GetCurrentThread() );
432 req->exit_code = exit_code;
433 wine_server_call( req );
434 last = reply->last;
436 SERVER_END_REQ;
438 if (last)
440 LdrShutdownProcess();
441 exit( exit_code );
443 else
445 LdrShutdownThread();
446 exit_thread( exit_code );
451 /***********************************************************************
452 * start_thread
454 * Startup routine for a newly created thread.
456 static void start_thread( struct startup_info *info )
458 TEB *teb = info->teb;
459 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
460 PRTL_THREAD_START_ROUTINE func = info->entry_point;
461 void *arg = info->entry_arg;
462 struct debug_info debug_info;
464 debug_info.str_pos = debug_info.strings;
465 debug_info.out_pos = debug_info.output;
466 thread_data->debug_info = &debug_info;
467 thread_data->pthread_id = pthread_self();
469 signal_init_thread( teb );
470 server_init_thread( func );
471 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
473 RtlAcquirePebLock();
474 InsertHeadList( &tls_links, &teb->TlsLinks );
475 RtlReleasePebLock();
477 /* NOTE: Windows does not have an exception handler around the call to
478 * the thread attach. We do for ease of debugging */
479 if (unhandled_exception_filter)
481 __TRY
483 call_thread_func( func, arg );
485 __EXCEPT(unhandled_exception_filter)
487 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
489 __ENDTRY
491 else
492 call_thread_func( func, arg );
496 /***********************************************************************
497 * RtlCreateUserThread (NTDLL.@)
499 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
500 BOOLEAN suspended, PVOID stack_addr,
501 SIZE_T stack_reserve, SIZE_T stack_commit,
502 PRTL_THREAD_START_ROUTINE start, void *param,
503 HANDLE *handle_ptr, CLIENT_ID *id )
505 sigset_t sigset;
506 pthread_t pthread_id;
507 pthread_attr_t attr;
508 struct ntdll_thread_data *thread_data = NULL;
509 struct ntdll_thread_regs *thread_regs;
510 struct startup_info *info = NULL;
511 void *addr = NULL;
512 HANDLE handle = 0;
513 TEB *teb;
514 DWORD tid = 0;
515 int request_pipe[2];
516 NTSTATUS status;
517 SIZE_T size;
519 if (process != NtCurrentProcess())
521 apc_call_t call;
522 apc_result_t result;
524 memset( &call, 0, sizeof(call) );
526 call.create_thread.type = APC_CREATE_THREAD;
527 call.create_thread.func = wine_server_client_ptr( start );
528 call.create_thread.arg = wine_server_client_ptr( param );
529 call.create_thread.reserve = stack_reserve;
530 call.create_thread.commit = stack_commit;
531 call.create_thread.suspend = suspended;
532 status = NTDLL_queue_process_apc( process, &call, &result );
533 if (status != STATUS_SUCCESS) return status;
535 if (result.create_thread.status == STATUS_SUCCESS)
537 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
538 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
539 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
541 return result.create_thread.status;
544 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
545 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
546 wine_server_send_fd( request_pipe[0] );
548 SERVER_START_REQ( new_thread )
550 req->access = THREAD_ALL_ACCESS;
551 req->attributes = 0; /* FIXME */
552 req->suspend = suspended;
553 req->request_fd = request_pipe[0];
554 if (!(status = wine_server_call( req )))
556 handle = wine_server_ptr_handle( reply->handle );
557 tid = reply->tid;
559 close( request_pipe[0] );
561 SERVER_END_REQ;
563 if (status)
565 close( request_pipe[1] );
566 return status;
569 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
571 addr = NULL;
572 size = sigstack_total_size;
573 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
574 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
575 goto error;
576 teb = addr;
577 teb->Peb = NtCurrentTeb()->Peb;
578 info = (struct startup_info *)(teb + 1);
579 info->teb = teb;
580 info->entry_point = start;
581 info->entry_arg = param;
583 if ((status = init_teb( teb ))) goto error;
585 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
586 teb->ClientId.UniqueThread = ULongToHandle(tid);
588 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
589 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
590 thread_data->request_fd = request_pipe[1];
592 /* inherit debug registers from parent thread */
593 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
594 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
595 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
596 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
597 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
598 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
600 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
602 pthread_attr_init( &attr );
603 pthread_attr_setstack( &attr, teb->DeallocationStack,
604 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
605 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
606 interlocked_xchg_add( &nb_threads, 1 );
607 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
609 interlocked_xchg_add( &nb_threads, -1 );
610 pthread_attr_destroy( &attr );
611 size = 0;
612 NtFreeVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
613 status = STATUS_NO_MEMORY;
614 goto error;
616 pthread_attr_destroy( &attr );
617 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
619 if (id) id->UniqueThread = ULongToHandle(tid);
620 if (handle_ptr) *handle_ptr = handle;
621 else NtClose( handle );
623 return STATUS_SUCCESS;
625 error:
626 if (thread_data) wine_ldt_free_fs( thread_data->fs );
627 if (addr)
629 size = 0;
630 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
632 if (handle) NtClose( handle );
633 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
634 close( request_pipe[1] );
635 return status;
639 /***********************************************************************
640 * RtlExitUserThread (NTDLL.@)
642 void WINAPI RtlExitUserThread( ULONG status )
644 BOOL last;
646 SERVER_START_REQ( terminate_thread )
648 /* send the exit code to the server */
649 req->handle = wine_server_obj_handle( GetCurrentThread() );
650 req->exit_code = status;
651 wine_server_call( req );
652 last = reply->last;
654 SERVER_END_REQ;
656 if (last)
658 LdrShutdownProcess();
659 exit( status );
661 else
663 LdrShutdownThread();
664 exit_thread( status );
669 /***********************************************************************
670 * NtOpenThread (NTDLL.@)
671 * ZwOpenThread (NTDLL.@)
673 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
674 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
676 NTSTATUS ret;
678 SERVER_START_REQ( open_thread )
680 req->tid = HandleToULong(id->UniqueThread);
681 req->access = access;
682 req->attributes = attr ? attr->Attributes : 0;
683 ret = wine_server_call( req );
684 *handle = wine_server_ptr_handle( reply->handle );
686 SERVER_END_REQ;
687 return ret;
691 /******************************************************************************
692 * NtSuspendThread (NTDLL.@)
693 * ZwSuspendThread (NTDLL.@)
695 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
697 NTSTATUS ret;
699 SERVER_START_REQ( suspend_thread )
701 req->handle = wine_server_obj_handle( handle );
702 if (!(ret = wine_server_call( req ))) *count = reply->count;
704 SERVER_END_REQ;
705 return ret;
709 /******************************************************************************
710 * NtResumeThread (NTDLL.@)
711 * ZwResumeThread (NTDLL.@)
713 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
715 NTSTATUS ret;
717 SERVER_START_REQ( resume_thread )
719 req->handle = wine_server_obj_handle( handle );
720 if (!(ret = wine_server_call( req ))) *count = reply->count;
722 SERVER_END_REQ;
723 return ret;
727 /******************************************************************************
728 * NtAlertResumeThread (NTDLL.@)
729 * ZwAlertResumeThread (NTDLL.@)
731 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
733 FIXME( "stub: should alert thread %p\n", handle );
734 return NtResumeThread( handle, count );
738 /******************************************************************************
739 * NtAlertThread (NTDLL.@)
740 * ZwAlertThread (NTDLL.@)
742 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
744 FIXME( "stub: %p\n", handle );
745 return STATUS_NOT_IMPLEMENTED;
749 /******************************************************************************
750 * NtTerminateThread (NTDLL.@)
751 * ZwTerminateThread (NTDLL.@)
753 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
755 NTSTATUS ret;
756 BOOL self, last;
758 SERVER_START_REQ( terminate_thread )
760 req->handle = wine_server_obj_handle( handle );
761 req->exit_code = exit_code;
762 ret = wine_server_call( req );
763 self = !ret && reply->self;
764 last = reply->last;
766 SERVER_END_REQ;
768 if (self)
770 if (last) _exit( exit_code );
771 else abort_thread( exit_code );
773 return ret;
777 /******************************************************************************
778 * NtQueueApcThread (NTDLL.@)
780 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
781 ULONG_PTR arg2, ULONG_PTR arg3 )
783 NTSTATUS ret;
784 SERVER_START_REQ( queue_apc )
786 req->handle = wine_server_obj_handle( handle );
787 if (func)
789 req->call.type = APC_USER;
790 req->call.user.func = wine_server_client_ptr( func );
791 req->call.user.args[0] = arg1;
792 req->call.user.args[1] = arg2;
793 req->call.user.args[2] = arg3;
795 else req->call.type = APC_NONE; /* wake up only */
796 ret = wine_server_call( req );
798 SERVER_END_REQ;
799 return ret;
803 /***********************************************************************
804 * NtSetContextThread (NTDLL.@)
805 * ZwSetContextThread (NTDLL.@)
807 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
809 NTSTATUS ret;
810 DWORD dummy, i;
811 BOOL self = FALSE;
813 #ifdef __i386__
814 /* on i386 debug registers always require a server call */
815 self = (handle == GetCurrentThread());
816 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
818 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
819 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
820 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
821 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
823 #endif
825 if (!self)
827 context_t server_context;
829 context_to_server( &server_context, context );
831 SERVER_START_REQ( set_thread_context )
833 req->handle = wine_server_obj_handle( handle );
834 req->suspend = 0;
835 wine_server_add_data( req, &server_context, sizeof(server_context) );
836 ret = wine_server_call( req );
837 self = reply->self;
839 SERVER_END_REQ;
841 if (ret == STATUS_PENDING)
843 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
845 for (i = 0; i < 100; i++)
847 SERVER_START_REQ( set_thread_context )
849 req->handle = wine_server_obj_handle( handle );
850 req->suspend = 0;
851 wine_server_add_data( req, &server_context, sizeof(server_context) );
852 ret = wine_server_call( req );
854 SERVER_END_REQ;
855 if (ret == STATUS_PENDING)
857 LARGE_INTEGER timeout;
858 timeout.QuadPart = -10000;
859 NtDelayExecution( FALSE, &timeout );
861 else break;
863 NtResumeThread( handle, &dummy );
865 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
868 if (ret) return ret;
871 if (self) set_cpu_context( context );
872 return STATUS_SUCCESS;
876 /* convert CPU-specific flags to generic server flags */
877 static inline unsigned int get_server_context_flags( DWORD flags )
879 unsigned int ret = 0;
881 flags &= ~0x3f; /* mask CPU id flags */
882 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
883 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
884 #ifdef CONTEXT_SEGMENTS
885 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
886 #endif
887 #ifdef CONTEXT_FLOATING_POINT
888 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
889 #endif
890 #ifdef CONTEXT_DEBUG_REGISTERS
891 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
892 #endif
893 #ifdef CONTEXT_EXTENDED_REGISTERS
894 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
895 #endif
896 return ret;
899 /***********************************************************************
900 * NtGetContextThread (NTDLL.@)
901 * ZwGetContextThread (NTDLL.@)
903 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
905 NTSTATUS ret;
906 DWORD dummy, i;
907 DWORD needed_flags = context->ContextFlags;
908 BOOL self = (handle == GetCurrentThread());
910 #ifdef __i386__
911 /* on i386 debug registers always require a server call */
912 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
913 #endif
915 if (!self)
917 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
918 context_t server_context;
920 SERVER_START_REQ( get_thread_context )
922 req->handle = wine_server_obj_handle( handle );
923 req->flags = server_flags;
924 req->suspend = 0;
925 wine_server_set_reply( req, &server_context, sizeof(server_context) );
926 ret = wine_server_call( req );
927 self = reply->self;
929 SERVER_END_REQ;
931 if (ret == STATUS_PENDING)
933 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
935 for (i = 0; i < 100; i++)
937 SERVER_START_REQ( get_thread_context )
939 req->handle = wine_server_obj_handle( handle );
940 req->flags = server_flags;
941 req->suspend = 0;
942 wine_server_set_reply( req, &server_context, sizeof(server_context) );
943 ret = wine_server_call( req );
945 SERVER_END_REQ;
946 if (ret == STATUS_PENDING)
948 LARGE_INTEGER timeout;
949 timeout.QuadPart = -10000;
950 NtDelayExecution( FALSE, &timeout );
952 else break;
954 NtResumeThread( handle, &dummy );
956 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
958 if (!ret) ret = context_from_server( context, &server_context );
959 if (ret) return ret;
960 needed_flags &= ~context->ContextFlags;
963 if (self)
965 if (needed_flags)
967 CONTEXT ctx;
968 RtlCaptureContext( &ctx );
969 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
970 context->ContextFlags |= ctx.ContextFlags & needed_flags;
972 #ifdef __i386__
973 /* update the cached version of the debug registers */
974 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
976 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
977 regs->dr0 = context->Dr0;
978 regs->dr1 = context->Dr1;
979 regs->dr2 = context->Dr2;
980 regs->dr3 = context->Dr3;
981 regs->dr6 = context->Dr6;
982 regs->dr7 = context->Dr7;
984 #endif
986 return STATUS_SUCCESS;
990 /******************************************************************************
991 * NtQueryInformationThread (NTDLL.@)
992 * ZwQueryInformationThread (NTDLL.@)
994 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
995 void *data, ULONG length, ULONG *ret_len )
997 NTSTATUS status;
999 switch(class)
1001 case ThreadBasicInformation:
1003 THREAD_BASIC_INFORMATION info;
1004 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1006 SERVER_START_REQ( get_thread_info )
1008 req->handle = wine_server_obj_handle( handle );
1009 req->tid_in = 0;
1010 if (!(status = wine_server_call( req )))
1012 info.ExitStatus = reply->exit_code;
1013 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
1014 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
1015 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
1016 info.AffinityMask = reply->affinity & affinity_mask;
1017 info.Priority = reply->priority;
1018 info.BasePriority = reply->priority; /* FIXME */
1021 SERVER_END_REQ;
1022 if (status == STATUS_SUCCESS)
1024 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1025 if (ret_len) *ret_len = min( length, sizeof(info) );
1028 return status;
1029 case ThreadAffinityMask:
1031 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1032 ULONG_PTR affinity = 0;
1034 SERVER_START_REQ( get_thread_info )
1036 req->handle = wine_server_obj_handle( handle );
1037 req->tid_in = 0;
1038 if (!(status = wine_server_call( req )))
1039 affinity = reply->affinity & affinity_mask;
1041 SERVER_END_REQ;
1042 if (status == STATUS_SUCCESS)
1044 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
1045 if (ret_len) *ret_len = min( length, sizeof(affinity) );
1048 return status;
1049 case ThreadTimes:
1051 KERNEL_USER_TIMES kusrt;
1052 /* We need to do a server call to get the creation time or exit time */
1053 /* This works on any thread */
1054 SERVER_START_REQ( get_thread_info )
1056 req->handle = wine_server_obj_handle( handle );
1057 req->tid_in = 0;
1058 status = wine_server_call( req );
1059 if (status == STATUS_SUCCESS)
1061 kusrt.CreateTime.QuadPart = reply->creation_time;
1062 kusrt.ExitTime.QuadPart = reply->exit_time;
1065 SERVER_END_REQ;
1066 if (status == STATUS_SUCCESS)
1068 /* We call times(2) for kernel time or user time */
1069 /* We can only (portably) do this for the current thread */
1070 if (handle == GetCurrentThread())
1072 struct tms time_buf;
1073 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1075 times(&time_buf);
1076 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1077 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1079 else
1081 static BOOL reported = FALSE;
1083 kusrt.KernelTime.QuadPart = 0;
1084 kusrt.UserTime.QuadPart = 0;
1085 if (reported)
1086 TRACE("Cannot get kerneltime or usertime of other threads\n");
1087 else
1089 FIXME("Cannot get kerneltime or usertime of other threads\n");
1090 reported = TRUE;
1093 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1094 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1097 return status;
1098 case ThreadDescriptorTableEntry:
1100 #ifdef __i386__
1101 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1102 if (length < sizeof(*tdi))
1103 status = STATUS_INFO_LENGTH_MISMATCH;
1104 else if (!(tdi->Selector & 4)) /* GDT selector */
1106 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1107 status = STATUS_SUCCESS;
1108 if (!sel) /* null selector */
1109 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1110 else
1112 tdi->Entry.BaseLow = 0;
1113 tdi->Entry.HighWord.Bits.BaseMid = 0;
1114 tdi->Entry.HighWord.Bits.BaseHi = 0;
1115 tdi->Entry.LimitLow = 0xffff;
1116 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1117 tdi->Entry.HighWord.Bits.Dpl = 3;
1118 tdi->Entry.HighWord.Bits.Sys = 0;
1119 tdi->Entry.HighWord.Bits.Pres = 1;
1120 tdi->Entry.HighWord.Bits.Granularity = 1;
1121 tdi->Entry.HighWord.Bits.Default_Big = 1;
1122 tdi->Entry.HighWord.Bits.Type = 0x12;
1123 /* it has to be one of the system GDT selectors */
1124 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1126 if (sel == (wine_get_cs() & ~3))
1127 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1128 else status = STATUS_ACCESS_DENIED;
1132 else
1134 SERVER_START_REQ( get_selector_entry )
1136 req->handle = wine_server_obj_handle( handle );
1137 req->entry = tdi->Selector >> 3;
1138 status = wine_server_call( req );
1139 if (!status)
1141 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1142 status = STATUS_ACCESS_VIOLATION;
1143 else
1145 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1146 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1147 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1151 SERVER_END_REQ;
1153 if (status == STATUS_SUCCESS && ret_len)
1154 /* yes, that's a bit strange, but it's the way it is */
1155 *ret_len = sizeof(LDT_ENTRY);
1156 #else
1157 status = STATUS_NOT_IMPLEMENTED;
1158 #endif
1159 return status;
1161 case ThreadAmILastThread:
1163 SERVER_START_REQ(get_thread_info)
1165 req->handle = wine_server_obj_handle( handle );
1166 req->tid_in = 0;
1167 status = wine_server_call( req );
1168 if (status == STATUS_SUCCESS)
1170 BOOLEAN last = reply->last;
1171 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1172 if (ret_len) *ret_len = min( length, sizeof(last) );
1175 SERVER_END_REQ;
1176 return status;
1178 case ThreadPriority:
1179 case ThreadBasePriority:
1180 case ThreadImpersonationToken:
1181 case ThreadEnableAlignmentFaultFixup:
1182 case ThreadEventPair_Reusable:
1183 case ThreadQuerySetWin32StartAddress:
1184 case ThreadZeroTlsCell:
1185 case ThreadPerformanceCount:
1186 case ThreadIdealProcessor:
1187 case ThreadPriorityBoost:
1188 case ThreadSetTlsArrayAddress:
1189 case ThreadIsIoPending:
1190 default:
1191 FIXME( "info class %d not supported yet\n", class );
1192 return STATUS_NOT_IMPLEMENTED;
1197 /******************************************************************************
1198 * NtSetInformationThread (NTDLL.@)
1199 * ZwSetInformationThread (NTDLL.@)
1201 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1202 LPCVOID data, ULONG length )
1204 NTSTATUS status;
1205 switch(class)
1207 case ThreadZeroTlsCell:
1208 if (handle == GetCurrentThread())
1210 LIST_ENTRY *entry;
1211 DWORD index;
1213 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1214 index = *(const DWORD *)data;
1215 if (index < TLS_MINIMUM_AVAILABLE)
1217 RtlAcquirePebLock();
1218 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1220 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1221 teb->TlsSlots[index] = 0;
1223 RtlReleasePebLock();
1225 else
1227 index -= TLS_MINIMUM_AVAILABLE;
1228 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1229 return STATUS_INVALID_PARAMETER;
1230 RtlAcquirePebLock();
1231 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1233 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1234 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1236 RtlReleasePebLock();
1238 return STATUS_SUCCESS;
1240 FIXME( "ZeroTlsCell not supported on other threads\n" );
1241 return STATUS_NOT_IMPLEMENTED;
1243 case ThreadImpersonationToken:
1245 const HANDLE *phToken = data;
1246 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1247 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1248 SERVER_START_REQ( set_thread_info )
1250 req->handle = wine_server_obj_handle( handle );
1251 req->token = wine_server_obj_handle( *phToken );
1252 req->mask = SET_THREAD_INFO_TOKEN;
1253 status = wine_server_call( req );
1255 SERVER_END_REQ;
1257 return status;
1258 case ThreadBasePriority:
1260 const DWORD *pprio = data;
1261 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1262 SERVER_START_REQ( set_thread_info )
1264 req->handle = wine_server_obj_handle( handle );
1265 req->priority = *pprio;
1266 req->mask = SET_THREAD_INFO_PRIORITY;
1267 status = wine_server_call( req );
1269 SERVER_END_REQ;
1271 return status;
1272 case ThreadAffinityMask:
1274 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1275 const ULONG_PTR *paff = data;
1276 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1277 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1278 SERVER_START_REQ( set_thread_info )
1280 req->handle = wine_server_obj_handle( handle );
1281 req->affinity = *paff;
1282 req->mask = SET_THREAD_INFO_AFFINITY;
1283 status = wine_server_call( req );
1285 SERVER_END_REQ;
1287 return status;
1288 case ThreadBasicInformation:
1289 case ThreadTimes:
1290 case ThreadPriority:
1291 case ThreadDescriptorTableEntry:
1292 case ThreadEnableAlignmentFaultFixup:
1293 case ThreadEventPair_Reusable:
1294 case ThreadQuerySetWin32StartAddress:
1295 case ThreadPerformanceCount:
1296 case ThreadAmILastThread:
1297 case ThreadIdealProcessor:
1298 case ThreadPriorityBoost:
1299 case ThreadSetTlsArrayAddress:
1300 case ThreadIsIoPending:
1301 default:
1302 FIXME( "info class %d not supported yet\n", class );
1303 return STATUS_NOT_IMPLEMENTED;