gdi32: PATH_ExtTextOut remove incorrect shift to DC origin.
[wine/hacks.git] / dlls / ntdll / thread.c
blob8c6d72c5e3095b5fdc5825065bcb4d239ab71b46
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( NULL );
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 SERVER_START_REQ( set_thread_context )
829 req->handle = wine_server_obj_handle( handle );
830 req->flags = context->ContextFlags;
831 req->suspend = 0;
832 wine_server_add_data( req, context, sizeof(*context) );
833 ret = wine_server_call( req );
834 self = reply->self;
836 SERVER_END_REQ;
838 if (ret == STATUS_PENDING)
840 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
842 for (i = 0; i < 100; i++)
844 SERVER_START_REQ( set_thread_context )
846 req->handle = wine_server_obj_handle( handle );
847 req->flags = context->ContextFlags;
848 req->suspend = 0;
849 wine_server_add_data( req, context, sizeof(*context) );
850 ret = wine_server_call( req );
852 SERVER_END_REQ;
853 if (ret == STATUS_PENDING)
855 LARGE_INTEGER timeout;
856 timeout.QuadPart = -10000;
857 NtDelayExecution( FALSE, &timeout );
859 else break;
861 NtResumeThread( handle, &dummy );
863 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
866 if (ret) return ret;
869 if (self) set_cpu_context( context );
870 return STATUS_SUCCESS;
874 /***********************************************************************
875 * NtGetContextThread (NTDLL.@)
876 * ZwGetContextThread (NTDLL.@)
878 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
880 NTSTATUS ret;
881 CONTEXT ctx;
882 DWORD dummy, i;
883 DWORD needed_flags = context->ContextFlags;
884 BOOL self = (handle == GetCurrentThread());
886 #ifdef __i386__
887 /* on i386 debug registers always require a server call */
888 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
889 #endif
891 if (!self)
893 SERVER_START_REQ( get_thread_context )
895 req->handle = wine_server_obj_handle( handle );
896 req->flags = context->ContextFlags;
897 req->suspend = 0;
898 wine_server_set_reply( req, &ctx, sizeof(ctx) );
899 ret = wine_server_call( req );
900 self = reply->self;
902 SERVER_END_REQ;
904 if (ret == STATUS_PENDING)
906 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
908 for (i = 0; i < 100; i++)
910 SERVER_START_REQ( get_thread_context )
912 req->handle = wine_server_obj_handle( handle );
913 req->flags = context->ContextFlags;
914 req->suspend = 0;
915 wine_server_set_reply( req, &ctx, sizeof(ctx) );
916 ret = wine_server_call( req );
918 SERVER_END_REQ;
919 if (ret == STATUS_PENDING)
921 LARGE_INTEGER timeout;
922 timeout.QuadPart = -10000;
923 NtDelayExecution( FALSE, &timeout );
925 else break;
927 NtResumeThread( handle, &dummy );
929 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
931 if (ret) return ret;
932 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
933 needed_flags &= ~ctx.ContextFlags;
936 if (self)
938 if (needed_flags)
940 RtlCaptureContext( &ctx );
941 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
943 #ifdef __i386__
944 /* update the cached version of the debug registers */
945 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
947 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
948 regs->dr0 = context->Dr0;
949 regs->dr1 = context->Dr1;
950 regs->dr2 = context->Dr2;
951 regs->dr3 = context->Dr3;
952 regs->dr6 = context->Dr6;
953 regs->dr7 = context->Dr7;
955 #endif
957 return STATUS_SUCCESS;
961 /******************************************************************************
962 * NtQueryInformationThread (NTDLL.@)
963 * ZwQueryInformationThread (NTDLL.@)
965 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
966 void *data, ULONG length, ULONG *ret_len )
968 NTSTATUS status;
970 switch(class)
972 case ThreadBasicInformation:
974 THREAD_BASIC_INFORMATION info;
975 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
977 SERVER_START_REQ( get_thread_info )
979 req->handle = wine_server_obj_handle( handle );
980 req->tid_in = 0;
981 if (!(status = wine_server_call( req )))
983 info.ExitStatus = reply->exit_code;
984 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
985 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
986 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
987 info.AffinityMask = reply->affinity & affinity_mask;
988 info.Priority = reply->priority;
989 info.BasePriority = reply->priority; /* FIXME */
992 SERVER_END_REQ;
993 if (status == STATUS_SUCCESS)
995 if (data) memcpy( data, &info, min( length, sizeof(info) ));
996 if (ret_len) *ret_len = min( length, sizeof(info) );
999 return status;
1000 case ThreadAffinityMask:
1002 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1003 ULONG_PTR affinity = 0;
1005 SERVER_START_REQ( get_thread_info )
1007 req->handle = wine_server_obj_handle( handle );
1008 req->tid_in = 0;
1009 if (!(status = wine_server_call( req )))
1010 affinity = reply->affinity & affinity_mask;
1012 SERVER_END_REQ;
1013 if (status == STATUS_SUCCESS)
1015 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
1016 if (ret_len) *ret_len = min( length, sizeof(affinity) );
1019 return status;
1020 case ThreadTimes:
1022 KERNEL_USER_TIMES kusrt;
1023 /* We need to do a server call to get the creation time or exit time */
1024 /* This works on any thread */
1025 SERVER_START_REQ( get_thread_info )
1027 req->handle = wine_server_obj_handle( handle );
1028 req->tid_in = 0;
1029 status = wine_server_call( req );
1030 if (status == STATUS_SUCCESS)
1032 kusrt.CreateTime.QuadPart = reply->creation_time;
1033 kusrt.ExitTime.QuadPart = reply->exit_time;
1036 SERVER_END_REQ;
1037 if (status == STATUS_SUCCESS)
1039 /* We call times(2) for kernel time or user time */
1040 /* We can only (portably) do this for the current thread */
1041 if (handle == GetCurrentThread())
1043 struct tms time_buf;
1044 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1046 times(&time_buf);
1047 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1048 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1050 else
1052 static BOOL reported = FALSE;
1054 kusrt.KernelTime.QuadPart = 0;
1055 kusrt.UserTime.QuadPart = 0;
1056 if (reported)
1057 TRACE("Cannot get kerneltime or usertime of other threads\n");
1058 else
1060 FIXME("Cannot get kerneltime or usertime of other threads\n");
1061 reported = TRUE;
1064 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1065 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1068 return status;
1069 case ThreadDescriptorTableEntry:
1071 #ifdef __i386__
1072 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1073 if (length < sizeof(*tdi))
1074 status = STATUS_INFO_LENGTH_MISMATCH;
1075 else if (!(tdi->Selector & 4)) /* GDT selector */
1077 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1078 status = STATUS_SUCCESS;
1079 if (!sel) /* null selector */
1080 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1081 else
1083 tdi->Entry.BaseLow = 0;
1084 tdi->Entry.HighWord.Bits.BaseMid = 0;
1085 tdi->Entry.HighWord.Bits.BaseHi = 0;
1086 tdi->Entry.LimitLow = 0xffff;
1087 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1088 tdi->Entry.HighWord.Bits.Dpl = 3;
1089 tdi->Entry.HighWord.Bits.Sys = 0;
1090 tdi->Entry.HighWord.Bits.Pres = 1;
1091 tdi->Entry.HighWord.Bits.Granularity = 1;
1092 tdi->Entry.HighWord.Bits.Default_Big = 1;
1093 tdi->Entry.HighWord.Bits.Type = 0x12;
1094 /* it has to be one of the system GDT selectors */
1095 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1097 if (sel == (wine_get_cs() & ~3))
1098 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1099 else status = STATUS_ACCESS_DENIED;
1103 else
1105 SERVER_START_REQ( get_selector_entry )
1107 req->handle = wine_server_obj_handle( handle );
1108 req->entry = tdi->Selector >> 3;
1109 status = wine_server_call( req );
1110 if (!status)
1112 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1113 status = STATUS_ACCESS_VIOLATION;
1114 else
1116 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1117 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1118 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1122 SERVER_END_REQ;
1124 if (status == STATUS_SUCCESS && ret_len)
1125 /* yes, that's a bit strange, but it's the way it is */
1126 *ret_len = sizeof(LDT_ENTRY);
1127 #else
1128 status = STATUS_NOT_IMPLEMENTED;
1129 #endif
1130 return status;
1132 case ThreadAmILastThread:
1134 SERVER_START_REQ(get_thread_info)
1136 req->handle = wine_server_obj_handle( handle );
1137 req->tid_in = 0;
1138 status = wine_server_call( req );
1139 if (status == STATUS_SUCCESS)
1141 BOOLEAN last = reply->last;
1142 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1143 if (ret_len) *ret_len = min( length, sizeof(last) );
1146 SERVER_END_REQ;
1147 return status;
1149 case ThreadPriority:
1150 case ThreadBasePriority:
1151 case ThreadImpersonationToken:
1152 case ThreadEnableAlignmentFaultFixup:
1153 case ThreadEventPair_Reusable:
1154 case ThreadQuerySetWin32StartAddress:
1155 case ThreadZeroTlsCell:
1156 case ThreadPerformanceCount:
1157 case ThreadIdealProcessor:
1158 case ThreadPriorityBoost:
1159 case ThreadSetTlsArrayAddress:
1160 case ThreadIsIoPending:
1161 default:
1162 FIXME( "info class %d not supported yet\n", class );
1163 return STATUS_NOT_IMPLEMENTED;
1168 /******************************************************************************
1169 * NtSetInformationThread (NTDLL.@)
1170 * ZwSetInformationThread (NTDLL.@)
1172 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1173 LPCVOID data, ULONG length )
1175 NTSTATUS status;
1176 switch(class)
1178 case ThreadZeroTlsCell:
1179 if (handle == GetCurrentThread())
1181 LIST_ENTRY *entry;
1182 DWORD index;
1184 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1185 index = *(const DWORD *)data;
1186 if (index < TLS_MINIMUM_AVAILABLE)
1188 RtlAcquirePebLock();
1189 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1191 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1192 teb->TlsSlots[index] = 0;
1194 RtlReleasePebLock();
1196 else
1198 index -= TLS_MINIMUM_AVAILABLE;
1199 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1200 return STATUS_INVALID_PARAMETER;
1201 RtlAcquirePebLock();
1202 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1204 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1205 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1207 RtlReleasePebLock();
1209 return STATUS_SUCCESS;
1211 FIXME( "ZeroTlsCell not supported on other threads\n" );
1212 return STATUS_NOT_IMPLEMENTED;
1214 case ThreadImpersonationToken:
1216 const HANDLE *phToken = data;
1217 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1218 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1219 SERVER_START_REQ( set_thread_info )
1221 req->handle = wine_server_obj_handle( handle );
1222 req->token = wine_server_obj_handle( *phToken );
1223 req->mask = SET_THREAD_INFO_TOKEN;
1224 status = wine_server_call( req );
1226 SERVER_END_REQ;
1228 return status;
1229 case ThreadBasePriority:
1231 const DWORD *pprio = data;
1232 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1233 SERVER_START_REQ( set_thread_info )
1235 req->handle = wine_server_obj_handle( handle );
1236 req->priority = *pprio;
1237 req->mask = SET_THREAD_INFO_PRIORITY;
1238 status = wine_server_call( req );
1240 SERVER_END_REQ;
1242 return status;
1243 case ThreadAffinityMask:
1245 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1246 const ULONG_PTR *paff = data;
1247 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1248 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1249 SERVER_START_REQ( set_thread_info )
1251 req->handle = wine_server_obj_handle( handle );
1252 req->affinity = *paff;
1253 req->mask = SET_THREAD_INFO_AFFINITY;
1254 status = wine_server_call( req );
1256 SERVER_END_REQ;
1258 return status;
1259 case ThreadBasicInformation:
1260 case ThreadTimes:
1261 case ThreadPriority:
1262 case ThreadDescriptorTableEntry:
1263 case ThreadEnableAlignmentFaultFixup:
1264 case ThreadEventPair_Reusable:
1265 case ThreadQuerySetWin32StartAddress:
1266 case ThreadPerformanceCount:
1267 case ThreadAmILastThread:
1268 case ThreadIdealProcessor:
1269 case ThreadPriorityBoost:
1270 case ThreadSetTlsArrayAddress:
1271 case ThreadIsIoPending:
1272 default:
1273 FIXME( "info class %d not supported yet\n", class );
1274 return STATUS_NOT_IMPLEMENTED;