ntdll: Move the abort_thread() function to the CPU-specific files to allow redefining it.
[wine/multimedia.git] / dlls / ntdll / thread.c
blob70ab2bf416e97bd1e5d4868a01c3da671914b10f
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 * get_unicode_string
131 * Copy a unicode string from the startup info.
133 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
135 str->Buffer = *dst;
136 str->Length = len;
137 str->MaximumLength = len + sizeof(WCHAR);
138 memcpy( str->Buffer, *src, len );
139 str->Buffer[len / sizeof(WCHAR)] = 0;
140 *src += len / sizeof(WCHAR);
141 *dst += len / sizeof(WCHAR) + 1;
144 /***********************************************************************
145 * init_user_process_params
147 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
149 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
151 void *ptr;
152 WCHAR *src, *dst;
153 SIZE_T info_size, env_size, size, alloc_size;
154 NTSTATUS status;
155 startup_info_t *info;
156 RTL_USER_PROCESS_PARAMETERS *params = NULL;
158 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
159 return STATUS_NO_MEMORY;
161 SERVER_START_REQ( get_startup_info )
163 wine_server_set_reply( req, info, data_size );
164 if (!(status = wine_server_call( req )))
166 data_size = wine_server_reply_size( reply );
167 info_size = reply->info_size;
168 env_size = data_size - info_size;
169 *exe_file = wine_server_ptr_handle( reply->exe_file );
172 SERVER_END_REQ;
173 if (status != STATUS_SUCCESS) goto done;
175 size = sizeof(*params);
176 size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
177 size += info->dllpath_len + sizeof(WCHAR);
178 size += info->imagepath_len + sizeof(WCHAR);
179 size += info->cmdline_len + sizeof(WCHAR);
180 size += info->title_len + sizeof(WCHAR);
181 size += info->desktop_len + sizeof(WCHAR);
182 size += info->shellinfo_len + sizeof(WCHAR);
183 size += info->runtime_len + sizeof(WCHAR);
185 alloc_size = size;
186 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &alloc_size,
187 MEM_COMMIT, PAGE_READWRITE );
188 if (status != STATUS_SUCCESS) goto done;
190 NtCurrentTeb()->Peb->ProcessParameters = params;
191 params->AllocationSize = alloc_size;
192 params->Size = size;
193 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
194 params->DebugFlags = info->debug_flags;
195 params->ConsoleHandle = wine_server_ptr_handle( info->console );
196 params->ConsoleFlags = info->console_flags;
197 params->hStdInput = wine_server_ptr_handle( info->hstdin );
198 params->hStdOutput = wine_server_ptr_handle( info->hstdout );
199 params->hStdError = wine_server_ptr_handle( info->hstderr );
200 params->dwX = info->x;
201 params->dwY = info->y;
202 params->dwXSize = info->xsize;
203 params->dwYSize = info->ysize;
204 params->dwXCountChars = info->xchars;
205 params->dwYCountChars = info->ychars;
206 params->dwFillAttribute = info->attribute;
207 params->dwFlags = info->flags;
208 params->wShowWindow = info->show;
210 src = (WCHAR *)(info + 1);
211 dst = (WCHAR *)(params + 1);
213 /* current directory needs more space */
214 get_unicode_string( &params->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
215 params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
216 dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
218 get_unicode_string( &params->DllPath, &src, &dst, info->dllpath_len );
219 get_unicode_string( &params->ImagePathName, &src, &dst, info->imagepath_len );
220 get_unicode_string( &params->CommandLine, &src, &dst, info->cmdline_len );
221 get_unicode_string( &params->WindowTitle, &src, &dst, info->title_len );
222 get_unicode_string( &params->Desktop, &src, &dst, info->desktop_len );
223 get_unicode_string( &params->ShellInfo, &src, &dst, info->shellinfo_len );
225 /* runtime info isn't a real string */
226 params->RuntimeInfo.Buffer = dst;
227 params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
228 memcpy( dst, src, info->runtime_len );
230 /* environment needs to be a separate memory block */
231 ptr = NULL;
232 alloc_size = max( 1, env_size );
233 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
234 MEM_COMMIT, PAGE_READWRITE );
235 if (status != STATUS_SUCCESS) goto done;
236 memcpy( ptr, (char *)info + info_size, env_size );
237 params->Environment = ptr;
239 done:
240 RtlFreeHeap( GetProcessHeap(), 0, info );
241 return status;
245 /***********************************************************************
246 * thread_init
248 * Setup the initial thread.
250 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
252 HANDLE thread_init(void)
254 PEB *peb;
255 TEB *teb;
256 void *addr;
257 SIZE_T size, info_size;
258 HANDLE exe_file = 0;
259 LARGE_INTEGER now;
260 struct ntdll_thread_data *thread_data;
261 static struct debug_info debug_info; /* debug info for initial thread */
263 virtual_init();
265 /* reserve space for shared user data */
267 addr = (void *)0x7ffe0000;
268 size = 0x10000;
269 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
270 user_shared_data = addr;
272 /* allocate and initialize the PEB */
274 addr = NULL;
275 size = sizeof(*peb);
276 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
277 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
278 peb = addr;
280 peb->NumberOfProcessors = 1;
281 peb->ProcessParameters = &params;
282 peb->TlsBitmap = &tls_bitmap;
283 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
284 peb->FlsBitmap = &fls_bitmap;
285 peb->LdrData = &ldr;
286 params.CurrentDirectory.DosPath.Buffer = current_dir;
287 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
288 params.wShowWindow = 1; /* SW_SHOWNORMAL */
289 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
290 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
291 sizeof(peb->TlsExpansionBitmapBits) * 8 );
292 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
293 InitializeListHead( &peb->FlsListHead );
294 InitializeListHead( &ldr.InLoadOrderModuleList );
295 InitializeListHead( &ldr.InMemoryOrderModuleList );
296 InitializeListHead( &ldr.InInitializationOrderModuleList );
297 InitializeListHead( &tls_links );
299 /* allocate and initialize the initial TEB */
301 sigstack_total_size = get_signal_stack_total_size();
302 while (1U << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
303 assert( 1U << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
304 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
306 addr = NULL;
307 size = sigstack_total_size;
308 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
309 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
310 teb = addr;
311 teb->Peb = peb;
312 init_teb( teb );
313 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
314 thread_data->debug_info = &debug_info;
315 InsertHeadList( &tls_links, &teb->TlsLinks );
317 signal_init_thread( teb );
318 virtual_init_threading();
320 debug_info.str_pos = debug_info.strings;
321 debug_info.out_pos = debug_info.output;
322 debug_init();
324 /* setup the server connection */
325 server_init_process();
326 info_size = server_init_thread( peb );
328 /* create the process heap */
329 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
331 MESSAGE( "wine: failed to create the process heap\n" );
332 exit(1);
335 /* allocate user parameters */
336 if (info_size)
338 init_user_process_params( info_size, &exe_file );
340 else
342 /* This is wine specific: we have no parent (we're started from unix)
343 * so, create a simple console with bare handles to unix stdio
345 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, &params.hStdInput );
346 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
347 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
350 /* initialize LDT locking */
351 wine_ldt_init_locking( ldt_lock, ldt_unlock );
353 /* initialize time values in user_shared_data */
354 NtQuerySystemTime( &now );
355 user_shared_data->SystemTime.LowPart = now.u.LowPart;
356 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
357 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
358 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
359 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
360 user_shared_data->TickCountMultiplier = 1 << 24;
362 return exe_file;
366 /***********************************************************************
367 * terminate_thread
369 void terminate_thread( int status )
371 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
372 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
374 close( ntdll_get_thread_data()->wait_fd[0] );
375 close( ntdll_get_thread_data()->wait_fd[1] );
376 close( ntdll_get_thread_data()->reply_fd );
377 close( ntdll_get_thread_data()->request_fd );
378 pthread_exit( UIntToPtr(status) );
382 /***********************************************************************
383 * exit_thread
385 void exit_thread( int status )
387 static void *prev_teb;
388 TEB *teb;
390 if (status) /* send the exit code to the server (0 is already the default) */
392 SERVER_START_REQ( terminate_thread )
394 req->handle = wine_server_obj_handle( GetCurrentThread() );
395 req->exit_code = status;
396 wine_server_call( req );
398 SERVER_END_REQ;
401 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
403 LdrShutdownProcess();
404 exit( status );
407 LdrShutdownThread();
408 RtlAcquirePebLock();
409 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
410 RtlReleasePebLock();
411 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
412 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
414 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
416 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
418 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
419 SIZE_T size;
421 pthread_join( thread_data->pthread_id, NULL );
422 wine_ldt_free_fs( thread_data->fs );
423 size = 0;
424 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
425 size = 0;
426 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
429 close( ntdll_get_thread_data()->wait_fd[0] );
430 close( ntdll_get_thread_data()->wait_fd[1] );
431 close( ntdll_get_thread_data()->reply_fd );
432 close( ntdll_get_thread_data()->request_fd );
433 pthread_exit( UIntToPtr(status) );
437 /***********************************************************************
438 * start_thread
440 * Startup routine for a newly created thread.
442 static void start_thread( struct startup_info *info )
444 TEB *teb = info->teb;
445 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
446 PRTL_THREAD_START_ROUTINE func = info->entry_point;
447 void *arg = info->entry_arg;
448 struct debug_info debug_info;
450 debug_info.str_pos = debug_info.strings;
451 debug_info.out_pos = debug_info.output;
452 thread_data->debug_info = &debug_info;
453 thread_data->pthread_id = pthread_self();
455 signal_init_thread( teb );
456 server_init_thread( func );
457 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
459 RtlAcquirePebLock();
460 InsertHeadList( &tls_links, &teb->TlsLinks );
461 RtlReleasePebLock();
463 MODULE_DllThreadAttach( NULL );
465 if (TRACE_ON(relay))
466 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
468 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
472 /***********************************************************************
473 * RtlCreateUserThread (NTDLL.@)
475 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
476 BOOLEAN suspended, PVOID stack_addr,
477 SIZE_T stack_reserve, SIZE_T stack_commit,
478 PRTL_THREAD_START_ROUTINE start, void *param,
479 HANDLE *handle_ptr, CLIENT_ID *id )
481 sigset_t sigset;
482 pthread_t pthread_id;
483 pthread_attr_t attr;
484 struct ntdll_thread_data *thread_data = NULL;
485 struct ntdll_thread_regs *thread_regs;
486 struct startup_info *info = NULL;
487 void *addr = NULL;
488 HANDLE handle = 0;
489 TEB *teb;
490 DWORD tid = 0;
491 int request_pipe[2];
492 NTSTATUS status;
493 SIZE_T size;
495 if (process != NtCurrentProcess())
497 apc_call_t call;
498 apc_result_t result;
500 memset( &call, 0, sizeof(call) );
502 call.create_thread.type = APC_CREATE_THREAD;
503 call.create_thread.func = wine_server_client_ptr( start );
504 call.create_thread.arg = wine_server_client_ptr( param );
505 call.create_thread.reserve = stack_reserve;
506 call.create_thread.commit = stack_commit;
507 call.create_thread.suspend = suspended;
508 status = NTDLL_queue_process_apc( process, &call, &result );
509 if (status != STATUS_SUCCESS) return status;
511 if (result.create_thread.status == STATUS_SUCCESS)
513 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
514 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
515 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
517 return result.create_thread.status;
520 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
521 wine_server_send_fd( request_pipe[0] );
523 SERVER_START_REQ( new_thread )
525 req->access = THREAD_ALL_ACCESS;
526 req->attributes = 0; /* FIXME */
527 req->suspend = suspended;
528 req->request_fd = request_pipe[0];
529 if (!(status = wine_server_call( req )))
531 handle = wine_server_ptr_handle( reply->handle );
532 tid = reply->tid;
534 close( request_pipe[0] );
536 SERVER_END_REQ;
538 if (status)
540 close( request_pipe[1] );
541 return status;
544 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
546 addr = NULL;
547 size = sigstack_total_size;
548 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
549 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
550 goto error;
551 teb = addr;
552 teb->Peb = NtCurrentTeb()->Peb;
553 info = (struct startup_info *)(teb + 1);
554 info->teb = teb;
555 info->entry_point = start;
556 info->entry_arg = param;
558 if ((status = init_teb( teb ))) goto error;
560 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
561 teb->ClientId.UniqueThread = ULongToHandle(tid);
563 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
564 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
565 thread_data->request_fd = request_pipe[1];
567 /* inherit debug registers from parent thread */
568 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
569 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
570 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
571 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
572 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
573 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
575 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
577 pthread_attr_init( &attr );
578 pthread_attr_setstack( &attr, teb->DeallocationStack,
579 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
580 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
581 interlocked_xchg_add( &nb_threads, 1 );
582 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
584 interlocked_xchg_add( &nb_threads, -1 );
585 pthread_attr_destroy( &attr );
586 size = 0;
587 NtFreeVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
588 status = STATUS_NO_MEMORY;
589 goto error;
591 pthread_attr_destroy( &attr );
592 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
594 if (id) id->UniqueThread = ULongToHandle(tid);
595 if (handle_ptr) *handle_ptr = handle;
596 else NtClose( handle );
598 return STATUS_SUCCESS;
600 error:
601 if (thread_data) wine_ldt_free_fs( thread_data->fs );
602 if (addr)
604 size = 0;
605 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
607 if (handle) NtClose( handle );
608 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
609 close( request_pipe[1] );
610 return status;
614 /***********************************************************************
615 * NtOpenThread (NTDLL.@)
616 * ZwOpenThread (NTDLL.@)
618 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
619 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
621 NTSTATUS ret;
623 SERVER_START_REQ( open_thread )
625 req->tid = HandleToULong(id->UniqueThread);
626 req->access = access;
627 req->attributes = attr ? attr->Attributes : 0;
628 ret = wine_server_call( req );
629 *handle = wine_server_ptr_handle( reply->handle );
631 SERVER_END_REQ;
632 return ret;
636 /******************************************************************************
637 * NtSuspendThread (NTDLL.@)
638 * ZwSuspendThread (NTDLL.@)
640 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
642 NTSTATUS ret;
644 SERVER_START_REQ( suspend_thread )
646 req->handle = wine_server_obj_handle( handle );
647 if (!(ret = wine_server_call( req ))) *count = reply->count;
649 SERVER_END_REQ;
650 return ret;
654 /******************************************************************************
655 * NtResumeThread (NTDLL.@)
656 * ZwResumeThread (NTDLL.@)
658 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
660 NTSTATUS ret;
662 SERVER_START_REQ( resume_thread )
664 req->handle = wine_server_obj_handle( handle );
665 if (!(ret = wine_server_call( req ))) *count = reply->count;
667 SERVER_END_REQ;
668 return ret;
672 /******************************************************************************
673 * NtAlertResumeThread (NTDLL.@)
674 * ZwAlertResumeThread (NTDLL.@)
676 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
678 FIXME( "stub: should alert thread %p\n", handle );
679 return NtResumeThread( handle, count );
683 /******************************************************************************
684 * NtAlertThread (NTDLL.@)
685 * ZwAlertThread (NTDLL.@)
687 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
689 FIXME( "stub: %p\n", handle );
690 return STATUS_NOT_IMPLEMENTED;
694 /******************************************************************************
695 * NtTerminateThread (NTDLL.@)
696 * ZwTerminateThread (NTDLL.@)
698 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
700 NTSTATUS ret;
701 BOOL self;
703 SERVER_START_REQ( terminate_thread )
705 req->handle = wine_server_obj_handle( handle );
706 req->exit_code = exit_code;
707 ret = wine_server_call( req );
708 self = !ret && reply->self;
710 SERVER_END_REQ;
712 if (self) abort_thread( exit_code );
713 return ret;
717 /******************************************************************************
718 * NtQueueApcThread (NTDLL.@)
720 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
721 ULONG_PTR arg2, ULONG_PTR arg3 )
723 NTSTATUS ret;
724 SERVER_START_REQ( queue_apc )
726 req->handle = wine_server_obj_handle( handle );
727 if (func)
729 req->call.type = APC_USER;
730 req->call.user.func = wine_server_client_ptr( func );
731 req->call.user.args[0] = arg1;
732 req->call.user.args[1] = arg2;
733 req->call.user.args[2] = arg3;
735 else req->call.type = APC_NONE; /* wake up only */
736 ret = wine_server_call( req );
738 SERVER_END_REQ;
739 return ret;
743 /***********************************************************************
744 * NtSetContextThread (NTDLL.@)
745 * ZwSetContextThread (NTDLL.@)
747 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
749 NTSTATUS ret;
750 DWORD dummy, i;
751 BOOL self = FALSE;
753 #ifdef __i386__
754 /* on i386 debug registers always require a server call */
755 self = (handle == GetCurrentThread());
756 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
758 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
759 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
760 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
761 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
763 #endif
765 if (!self)
767 context_t server_context;
769 context_to_server( &server_context, context );
771 SERVER_START_REQ( set_thread_context )
773 req->handle = wine_server_obj_handle( handle );
774 req->suspend = 0;
775 wine_server_add_data( req, &server_context, sizeof(server_context) );
776 ret = wine_server_call( req );
777 self = reply->self;
779 SERVER_END_REQ;
781 if (ret == STATUS_PENDING)
783 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
785 for (i = 0; i < 100; i++)
787 SERVER_START_REQ( set_thread_context )
789 req->handle = wine_server_obj_handle( handle );
790 req->suspend = 0;
791 wine_server_add_data( req, &server_context, sizeof(server_context) );
792 ret = wine_server_call( req );
794 SERVER_END_REQ;
795 if (ret == STATUS_PENDING)
797 LARGE_INTEGER timeout;
798 timeout.QuadPart = -10000;
799 NtDelayExecution( FALSE, &timeout );
801 else break;
803 NtResumeThread( handle, &dummy );
805 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
808 if (ret) return ret;
811 if (self) set_cpu_context( context );
812 return STATUS_SUCCESS;
816 /* convert CPU-specific flags to generic server flags */
817 static inline unsigned int get_server_context_flags( DWORD flags )
819 unsigned int ret = 0;
821 flags &= 0x3f; /* mask CPU id flags */
822 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
823 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
824 #ifdef CONTEXT_SEGMENTS
825 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
826 #endif
827 #ifdef CONTEXT_FLOATING_POINT
828 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
829 #endif
830 #ifdef CONTEXT_DEBUG_REGISTERS
831 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
832 #endif
833 #ifdef CONTEXT_EXTENDED_REGISTERS
834 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
835 #endif
836 return ret;
839 /***********************************************************************
840 * NtGetContextThread (NTDLL.@)
841 * ZwGetContextThread (NTDLL.@)
843 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
845 NTSTATUS ret;
846 DWORD dummy, i;
847 DWORD needed_flags = context->ContextFlags;
848 BOOL self = (handle == GetCurrentThread());
850 #ifdef __i386__
851 /* on i386 debug registers always require a server call */
852 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
853 #endif
855 if (!self)
857 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
858 context_t server_context;
860 SERVER_START_REQ( get_thread_context )
862 req->handle = wine_server_obj_handle( handle );
863 req->flags = server_flags;
864 req->suspend = 0;
865 wine_server_set_reply( req, &server_context, sizeof(server_context) );
866 ret = wine_server_call( req );
867 self = reply->self;
869 SERVER_END_REQ;
871 if (ret == STATUS_PENDING)
873 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
875 for (i = 0; i < 100; i++)
877 SERVER_START_REQ( get_thread_context )
879 req->handle = wine_server_obj_handle( handle );
880 req->flags = server_flags;
881 req->suspend = 0;
882 wine_server_set_reply( req, &server_context, sizeof(server_context) );
883 ret = wine_server_call( req );
885 SERVER_END_REQ;
886 if (ret == STATUS_PENDING)
888 LARGE_INTEGER timeout;
889 timeout.QuadPart = -10000;
890 NtDelayExecution( FALSE, &timeout );
892 else break;
894 NtResumeThread( handle, &dummy );
896 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
898 if (!ret) ret = context_from_server( context, &server_context );
899 if (ret) return ret;
900 needed_flags &= ~context->ContextFlags;
903 if (self)
905 if (needed_flags)
907 CONTEXT ctx;
908 RtlCaptureContext( &ctx );
909 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
910 context->ContextFlags |= ctx.ContextFlags & needed_flags;
912 #ifdef __i386__
913 /* update the cached version of the debug registers */
914 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
916 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
917 regs->dr0 = context->Dr0;
918 regs->dr1 = context->Dr1;
919 regs->dr2 = context->Dr2;
920 regs->dr3 = context->Dr3;
921 regs->dr6 = context->Dr6;
922 regs->dr7 = context->Dr7;
924 #endif
926 return STATUS_SUCCESS;
930 /******************************************************************************
931 * NtQueryInformationThread (NTDLL.@)
932 * ZwQueryInformationThread (NTDLL.@)
934 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
935 void *data, ULONG length, ULONG *ret_len )
937 NTSTATUS status;
939 switch(class)
941 case ThreadBasicInformation:
943 THREAD_BASIC_INFORMATION info;
944 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
946 SERVER_START_REQ( get_thread_info )
948 req->handle = wine_server_obj_handle( handle );
949 req->tid_in = 0;
950 if (!(status = wine_server_call( req )))
952 info.ExitStatus = reply->exit_code;
953 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
954 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
955 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
956 info.AffinityMask = reply->affinity & affinity_mask;
957 info.Priority = reply->priority;
958 info.BasePriority = reply->priority; /* FIXME */
961 SERVER_END_REQ;
962 if (status == STATUS_SUCCESS)
964 if (data) memcpy( data, &info, min( length, sizeof(info) ));
965 if (ret_len) *ret_len = min( length, sizeof(info) );
968 return status;
969 case ThreadAffinityMask:
971 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
972 ULONG_PTR affinity = 0;
974 SERVER_START_REQ( get_thread_info )
976 req->handle = wine_server_obj_handle( handle );
977 req->tid_in = 0;
978 if (!(status = wine_server_call( req )))
979 affinity = reply->affinity & affinity_mask;
981 SERVER_END_REQ;
982 if (status == STATUS_SUCCESS)
984 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
985 if (ret_len) *ret_len = min( length, sizeof(affinity) );
988 return status;
989 case ThreadTimes:
991 KERNEL_USER_TIMES kusrt;
992 /* We need to do a server call to get the creation time or exit time */
993 /* This works on any thread */
994 SERVER_START_REQ( get_thread_info )
996 req->handle = wine_server_obj_handle( handle );
997 req->tid_in = 0;
998 status = wine_server_call( req );
999 if (status == STATUS_SUCCESS)
1001 kusrt.CreateTime.QuadPart = reply->creation_time;
1002 kusrt.ExitTime.QuadPart = reply->exit_time;
1005 SERVER_END_REQ;
1006 if (status == STATUS_SUCCESS)
1008 /* We call times(2) for kernel time or user time */
1009 /* We can only (portably) do this for the current thread */
1010 if (handle == GetCurrentThread())
1012 struct tms time_buf;
1013 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1015 times(&time_buf);
1016 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1017 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1019 else
1021 static BOOL reported = FALSE;
1023 kusrt.KernelTime.QuadPart = 0;
1024 kusrt.UserTime.QuadPart = 0;
1025 if (reported)
1026 TRACE("Cannot get kerneltime or usertime of other threads\n");
1027 else
1029 FIXME("Cannot get kerneltime or usertime of other threads\n");
1030 reported = TRUE;
1033 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1034 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1037 return status;
1038 case ThreadDescriptorTableEntry:
1040 #ifdef __i386__
1041 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1042 if (length < sizeof(*tdi))
1043 status = STATUS_INFO_LENGTH_MISMATCH;
1044 else if (!(tdi->Selector & 4)) /* GDT selector */
1046 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1047 status = STATUS_SUCCESS;
1048 if (!sel) /* null selector */
1049 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1050 else
1052 tdi->Entry.BaseLow = 0;
1053 tdi->Entry.HighWord.Bits.BaseMid = 0;
1054 tdi->Entry.HighWord.Bits.BaseHi = 0;
1055 tdi->Entry.LimitLow = 0xffff;
1056 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1057 tdi->Entry.HighWord.Bits.Dpl = 3;
1058 tdi->Entry.HighWord.Bits.Sys = 0;
1059 tdi->Entry.HighWord.Bits.Pres = 1;
1060 tdi->Entry.HighWord.Bits.Granularity = 1;
1061 tdi->Entry.HighWord.Bits.Default_Big = 1;
1062 tdi->Entry.HighWord.Bits.Type = 0x12;
1063 /* it has to be one of the system GDT selectors */
1064 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1066 if (sel == (wine_get_cs() & ~3))
1067 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1068 else status = STATUS_ACCESS_DENIED;
1072 else
1074 SERVER_START_REQ( get_selector_entry )
1076 req->handle = wine_server_obj_handle( handle );
1077 req->entry = tdi->Selector >> 3;
1078 status = wine_server_call( req );
1079 if (!status)
1081 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1082 status = STATUS_ACCESS_VIOLATION;
1083 else
1085 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1086 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1087 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1091 SERVER_END_REQ;
1093 if (status == STATUS_SUCCESS && ret_len)
1094 /* yes, that's a bit strange, but it's the way it is */
1095 *ret_len = sizeof(LDT_ENTRY);
1096 #else
1097 status = STATUS_NOT_IMPLEMENTED;
1098 #endif
1099 return status;
1101 case ThreadAmILastThread:
1103 SERVER_START_REQ(get_thread_info)
1105 req->handle = wine_server_obj_handle( handle );
1106 req->tid_in = 0;
1107 status = wine_server_call( req );
1108 if (status == STATUS_SUCCESS)
1110 BOOLEAN last = reply->last;
1111 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1112 if (ret_len) *ret_len = min( length, sizeof(last) );
1115 SERVER_END_REQ;
1116 return status;
1118 case ThreadPriority:
1119 case ThreadBasePriority:
1120 case ThreadImpersonationToken:
1121 case ThreadEnableAlignmentFaultFixup:
1122 case ThreadEventPair_Reusable:
1123 case ThreadQuerySetWin32StartAddress:
1124 case ThreadZeroTlsCell:
1125 case ThreadPerformanceCount:
1126 case ThreadIdealProcessor:
1127 case ThreadPriorityBoost:
1128 case ThreadSetTlsArrayAddress:
1129 case ThreadIsIoPending:
1130 default:
1131 FIXME( "info class %d not supported yet\n", class );
1132 return STATUS_NOT_IMPLEMENTED;
1137 /******************************************************************************
1138 * NtSetInformationThread (NTDLL.@)
1139 * ZwSetInformationThread (NTDLL.@)
1141 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1142 LPCVOID data, ULONG length )
1144 NTSTATUS status;
1145 switch(class)
1147 case ThreadZeroTlsCell:
1148 if (handle == GetCurrentThread())
1150 LIST_ENTRY *entry;
1151 DWORD index;
1153 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1154 index = *(const DWORD *)data;
1155 if (index < TLS_MINIMUM_AVAILABLE)
1157 RtlAcquirePebLock();
1158 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1160 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1161 teb->TlsSlots[index] = 0;
1163 RtlReleasePebLock();
1165 else
1167 index -= TLS_MINIMUM_AVAILABLE;
1168 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1169 return STATUS_INVALID_PARAMETER;
1170 RtlAcquirePebLock();
1171 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1173 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1174 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1176 RtlReleasePebLock();
1178 return STATUS_SUCCESS;
1180 FIXME( "ZeroTlsCell not supported on other threads\n" );
1181 return STATUS_NOT_IMPLEMENTED;
1183 case ThreadImpersonationToken:
1185 const HANDLE *phToken = data;
1186 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1187 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1188 SERVER_START_REQ( set_thread_info )
1190 req->handle = wine_server_obj_handle( handle );
1191 req->token = wine_server_obj_handle( *phToken );
1192 req->mask = SET_THREAD_INFO_TOKEN;
1193 status = wine_server_call( req );
1195 SERVER_END_REQ;
1197 return status;
1198 case ThreadBasePriority:
1200 const DWORD *pprio = data;
1201 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1202 SERVER_START_REQ( set_thread_info )
1204 req->handle = wine_server_obj_handle( handle );
1205 req->priority = *pprio;
1206 req->mask = SET_THREAD_INFO_PRIORITY;
1207 status = wine_server_call( req );
1209 SERVER_END_REQ;
1211 return status;
1212 case ThreadAffinityMask:
1214 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1215 const ULONG_PTR *paff = data;
1216 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1217 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1218 SERVER_START_REQ( set_thread_info )
1220 req->handle = wine_server_obj_handle( handle );
1221 req->affinity = *paff;
1222 req->mask = SET_THREAD_INFO_AFFINITY;
1223 status = wine_server_call( req );
1225 SERVER_END_REQ;
1227 return status;
1228 case ThreadBasicInformation:
1229 case ThreadTimes:
1230 case ThreadPriority:
1231 case ThreadDescriptorTableEntry:
1232 case ThreadEnableAlignmentFaultFixup:
1233 case ThreadEventPair_Reusable:
1234 case ThreadQuerySetWin32StartAddress:
1235 case ThreadPerformanceCount:
1236 case ThreadAmILastThread:
1237 case ThreadIdealProcessor:
1238 case ThreadPriorityBoost:
1239 case ThreadSetTlsArrayAddress:
1240 case ThreadIsIoPending:
1241 default:
1242 FIXME( "info class %d not supported yet\n", class );
1243 return STATUS_NOT_IMPLEMENTED;