wineoss.drv: Avoid potential overflow (Coverity).
[wine.git] / dlls / ntdll / thread.c
blob0b681859b2719c9362915403b00b1a380e92a793
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
33 #ifdef HAVE_SYS_SYSCALL_H
34 #include <sys/syscall.h>
35 #endif
37 #define NONAMELESSUNION
38 #include "ntstatus.h"
39 #define WIN32_NO_STATUS
40 #include "winternl.h"
41 #include "wine/library.h"
42 #include "wine/server.h"
43 #include "wine/debug.h"
44 #include "ntdll_misc.h"
45 #include "ddk/wdm.h"
46 #include "wine/exception.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(thread);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
53 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
55 /* info passed to a starting thread */
56 struct startup_info
58 TEB *teb;
59 PRTL_THREAD_START_ROUTINE entry_point;
60 void *entry_arg;
63 static PEB *peb;
64 static PEB_LDR_DATA ldr;
65 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
66 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
67 static RTL_BITMAP tls_bitmap;
68 static RTL_BITMAP tls_expansion_bitmap;
69 static RTL_BITMAP fls_bitmap;
70 static int nb_threads = 1;
72 /***********************************************************************
73 * get_unicode_string
75 * Copy a unicode string from the startup info.
77 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
79 str->Buffer = *dst;
80 str->Length = len;
81 str->MaximumLength = len + sizeof(WCHAR);
82 memcpy( str->Buffer, *src, len );
83 str->Buffer[len / sizeof(WCHAR)] = 0;
84 *src += len / sizeof(WCHAR);
85 *dst += len / sizeof(WCHAR) + 1;
88 /***********************************************************************
89 * init_user_process_params
91 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
93 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
95 void *ptr;
96 WCHAR *src, *dst;
97 SIZE_T info_size, env_size, size, alloc_size;
98 NTSTATUS status;
99 startup_info_t *info;
100 RTL_USER_PROCESS_PARAMETERS *params = NULL;
102 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
103 return STATUS_NO_MEMORY;
105 SERVER_START_REQ( get_startup_info )
107 wine_server_set_reply( req, info, data_size );
108 if (!(status = wine_server_call( req )))
110 data_size = wine_server_reply_size( reply );
111 info_size = reply->info_size;
112 env_size = data_size - info_size;
113 *exe_file = wine_server_ptr_handle( reply->exe_file );
116 SERVER_END_REQ;
117 if (status != STATUS_SUCCESS) goto done;
119 size = sizeof(*params);
120 size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
121 size += info->dllpath_len + sizeof(WCHAR);
122 size += info->imagepath_len + sizeof(WCHAR);
123 size += info->cmdline_len + sizeof(WCHAR);
124 size += info->title_len + sizeof(WCHAR);
125 size += info->desktop_len + sizeof(WCHAR);
126 size += info->shellinfo_len + sizeof(WCHAR);
127 size += info->runtime_len + sizeof(WCHAR);
129 alloc_size = size;
130 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &alloc_size,
131 MEM_COMMIT, PAGE_READWRITE );
132 if (status != STATUS_SUCCESS) goto done;
134 NtCurrentTeb()->Peb->ProcessParameters = params;
135 params->AllocationSize = alloc_size;
136 params->Size = size;
137 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
138 params->DebugFlags = info->debug_flags;
139 params->ConsoleHandle = wine_server_ptr_handle( info->console );
140 params->ConsoleFlags = info->console_flags;
141 params->hStdInput = wine_server_ptr_handle( info->hstdin );
142 params->hStdOutput = wine_server_ptr_handle( info->hstdout );
143 params->hStdError = wine_server_ptr_handle( info->hstderr );
144 params->dwX = info->x;
145 params->dwY = info->y;
146 params->dwXSize = info->xsize;
147 params->dwYSize = info->ysize;
148 params->dwXCountChars = info->xchars;
149 params->dwYCountChars = info->ychars;
150 params->dwFillAttribute = info->attribute;
151 params->dwFlags = info->flags;
152 params->wShowWindow = info->show;
154 src = (WCHAR *)(info + 1);
155 dst = (WCHAR *)(params + 1);
157 /* current directory needs more space */
158 get_unicode_string( &params->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
159 params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
160 dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
162 get_unicode_string( &params->DllPath, &src, &dst, info->dllpath_len );
163 get_unicode_string( &params->ImagePathName, &src, &dst, info->imagepath_len );
164 get_unicode_string( &params->CommandLine, &src, &dst, info->cmdline_len );
165 get_unicode_string( &params->WindowTitle, &src, &dst, info->title_len );
166 get_unicode_string( &params->Desktop, &src, &dst, info->desktop_len );
167 get_unicode_string( &params->ShellInfo, &src, &dst, info->shellinfo_len );
169 /* runtime info isn't a real string */
170 params->RuntimeInfo.Buffer = dst;
171 params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
172 memcpy( dst, src, info->runtime_len );
174 /* environment needs to be a separate memory block */
175 ptr = NULL;
176 alloc_size = max( 1, env_size );
177 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
178 MEM_COMMIT, PAGE_READWRITE );
179 if (status != STATUS_SUCCESS) goto done;
180 memcpy( ptr, (char *)info + info_size, env_size );
181 params->Environment = ptr;
183 done:
184 RtlFreeHeap( GetProcessHeap(), 0, info );
185 return status;
188 #ifdef __APPLE__
189 #include <mach/mach.h>
190 #include <mach/mach_error.h>
192 static ULONG64 get_dyld_image_info_addr(void)
194 ULONG64 ret = 0;
195 #ifdef TASK_DYLD_INFO
196 struct task_dyld_info dyld_info;
197 mach_msg_type_number_t size = TASK_DYLD_INFO_COUNT;
198 if (task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&dyld_info, &size) == KERN_SUCCESS)
199 ret = dyld_info.all_image_info_addr;
200 #endif
201 return ret;
203 #endif /* __APPLE__ */
205 /***********************************************************************
206 * thread_init
208 * Setup the initial thread.
210 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
212 HANDLE thread_init(void)
214 TEB *teb;
215 void *addr;
216 SIZE_T size, info_size;
217 HANDLE exe_file = 0;
218 LARGE_INTEGER now;
219 NTSTATUS status;
220 struct ntdll_thread_data *thread_data;
221 static struct debug_info debug_info; /* debug info for initial thread */
222 #ifdef __APPLE__
223 ULONG64 dyld_image_info;
224 #endif
226 virtual_init();
228 /* reserve space for shared user data */
230 addr = (void *)0x7ffe0000;
231 size = 0x10000;
232 status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
233 MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
234 if (status)
236 MESSAGE( "wine: failed to map the shared user data: %08x\n", status );
237 exit(1);
239 user_shared_data = addr;
241 /* allocate and initialize the PEB */
243 addr = NULL;
244 size = sizeof(*peb);
245 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
246 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
247 peb = addr;
249 peb->ProcessParameters = &params;
250 peb->TlsBitmap = &tls_bitmap;
251 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
252 peb->FlsBitmap = &fls_bitmap;
253 peb->LdrData = &ldr;
254 params.CurrentDirectory.DosPath.Buffer = current_dir;
255 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
256 params.wShowWindow = 1; /* SW_SHOWNORMAL */
257 ldr.Length = sizeof(ldr);
258 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
259 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
260 sizeof(peb->TlsExpansionBitmapBits) * 8 );
261 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
262 RtlSetBits( peb->TlsBitmap, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
263 RtlSetBits( peb->FlsBitmap, 0, 1 );
264 InitializeListHead( &peb->FlsListHead );
265 InitializeListHead( &ldr.InLoadOrderModuleList );
266 InitializeListHead( &ldr.InMemoryOrderModuleList );
267 InitializeListHead( &ldr.InInitializationOrderModuleList );
268 #ifdef __APPLE__
269 dyld_image_info = get_dyld_image_info_addr();
270 #ifdef __LP64__
271 #ifdef WORDS_BIGENDIAN
272 peb->Reserved[1] = dyld_image_info & 0xFFFFFFFF;
273 peb->Reserved[0] = dyld_image_info >> 32;
274 #else
275 peb->Reserved[0] = dyld_image_info & 0xFFFFFFFF;
276 peb->Reserved[1] = dyld_image_info >> 32;
277 #endif
278 #else
279 peb->Reserved[0] = dyld_image_info & 0xFFFFFFFF;
280 #endif
281 #endif
284 * Starting with Vista, the first user to log on has session id 1.
285 * Session id 0 is for processes that don't interact with the user (like services).
287 peb->SessionId = 1;
289 /* allocate and initialize the initial TEB */
291 signal_alloc_thread( &teb );
292 teb->Peb = peb;
293 teb->Tib.StackBase = (void *)~0UL;
294 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
295 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
297 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
298 thread_data->request_fd = -1;
299 thread_data->reply_fd = -1;
300 thread_data->wait_fd[0] = -1;
301 thread_data->wait_fd[1] = -1;
302 thread_data->debug_info = &debug_info;
303 InsertHeadList( &tls_links, &teb->TlsLinks );
305 signal_init_thread( teb );
306 virtual_init_threading();
308 debug_info.str_pos = debug_info.strings;
309 debug_info.out_pos = debug_info.output;
310 debug_init();
312 /* setup the server connection */
313 server_init_process();
314 info_size = server_init_thread( peb );
316 /* create the process heap */
317 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
319 MESSAGE( "wine: failed to create the process heap\n" );
320 exit(1);
323 /* allocate user parameters */
324 if (info_size)
326 init_user_process_params( info_size, &exe_file );
328 else
330 if (isatty(0) || isatty(1) || isatty(2))
331 params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
332 if (!isatty(0))
333 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, &params.hStdInput );
334 if (!isatty(1))
335 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
336 if (!isatty(2))
337 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
340 /* initialize time values in user_shared_data */
341 NtQuerySystemTime( &now );
342 user_shared_data->SystemTime.LowPart = now.u.LowPart;
343 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
344 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
345 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
346 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
347 user_shared_data->TickCountMultiplier = 1 << 24;
349 fill_cpu_info();
351 NtCreateKeyedEvent( &keyed_event, GENERIC_READ | GENERIC_WRITE, NULL, 0 );
353 return exe_file;
357 /***********************************************************************
358 * terminate_thread
360 void terminate_thread( int status )
362 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
363 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
365 close( ntdll_get_thread_data()->wait_fd[0] );
366 close( ntdll_get_thread_data()->wait_fd[1] );
367 close( ntdll_get_thread_data()->reply_fd );
368 close( ntdll_get_thread_data()->request_fd );
369 pthread_exit( UIntToPtr(status) );
373 /***********************************************************************
374 * exit_thread
376 void exit_thread( int status )
378 static void *prev_teb;
379 TEB *teb;
381 if (status) /* send the exit code to the server (0 is already the default) */
383 SERVER_START_REQ( terminate_thread )
385 req->handle = wine_server_obj_handle( GetCurrentThread() );
386 req->exit_code = status;
387 wine_server_call( req );
389 SERVER_END_REQ;
392 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
394 LdrShutdownProcess();
395 exit( status );
398 LdrShutdownThread();
399 RtlFreeThreadActivationContextStack();
401 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
403 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
405 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
407 if (thread_data->pthread_id)
409 pthread_join( thread_data->pthread_id, NULL );
410 signal_free_thread( teb );
414 close( ntdll_get_thread_data()->wait_fd[0] );
415 close( ntdll_get_thread_data()->wait_fd[1] );
416 close( ntdll_get_thread_data()->reply_fd );
417 close( ntdll_get_thread_data()->request_fd );
418 pthread_exit( UIntToPtr(status) );
422 /***********************************************************************
423 * start_thread
425 * Startup routine for a newly created thread.
427 static void start_thread( struct startup_info *info )
429 TEB *teb = info->teb;
430 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
431 PRTL_THREAD_START_ROUTINE func = info->entry_point;
432 void *arg = info->entry_arg;
433 struct debug_info debug_info;
435 debug_info.str_pos = debug_info.strings;
436 debug_info.out_pos = debug_info.output;
437 thread_data->debug_info = &debug_info;
438 thread_data->pthread_id = pthread_self();
440 signal_init_thread( teb );
441 server_init_thread( func );
442 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
444 MODULE_DllThreadAttach( NULL );
446 if (TRACE_ON(relay))
447 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
449 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
453 /***********************************************************************
454 * RtlCreateUserThread (NTDLL.@)
456 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
457 BOOLEAN suspended, PVOID stack_addr,
458 SIZE_T stack_reserve, SIZE_T stack_commit,
459 PRTL_THREAD_START_ROUTINE start, void *param,
460 HANDLE *handle_ptr, CLIENT_ID *id )
462 sigset_t sigset;
463 pthread_t pthread_id;
464 pthread_attr_t attr;
465 struct ntdll_thread_data *thread_data;
466 struct startup_info *info;
467 HANDLE handle = 0, actctx = 0;
468 TEB *teb = NULL;
469 DWORD tid = 0;
470 int request_pipe[2];
471 NTSTATUS status;
473 if (process != NtCurrentProcess())
475 apc_call_t call;
476 apc_result_t result;
478 memset( &call, 0, sizeof(call) );
480 call.create_thread.type = APC_CREATE_THREAD;
481 call.create_thread.func = wine_server_client_ptr( start );
482 call.create_thread.arg = wine_server_client_ptr( param );
483 call.create_thread.reserve = stack_reserve;
484 call.create_thread.commit = stack_commit;
485 call.create_thread.suspend = suspended;
486 status = server_queue_process_apc( process, &call, &result );
487 if (status != STATUS_SUCCESS) return status;
489 if (result.create_thread.status == STATUS_SUCCESS)
491 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
492 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
493 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
495 return result.create_thread.status;
498 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
499 wine_server_send_fd( request_pipe[0] );
501 SERVER_START_REQ( new_thread )
503 req->access = THREAD_ALL_ACCESS;
504 req->attributes = 0; /* FIXME */
505 req->suspend = suspended;
506 req->request_fd = request_pipe[0];
507 if (!(status = wine_server_call( req )))
509 handle = wine_server_ptr_handle( reply->handle );
510 tid = reply->tid;
512 close( request_pipe[0] );
514 SERVER_END_REQ;
516 if (status)
518 close( request_pipe[1] );
519 return status;
522 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
524 if ((status = signal_alloc_thread( &teb ))) goto error;
526 teb->Peb = NtCurrentTeb()->Peb;
527 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
528 teb->ClientId.UniqueThread = ULongToHandle(tid);
529 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
530 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
532 /* create default activation context frame for new thread */
533 RtlGetActiveActivationContext(&actctx);
534 if (actctx)
536 RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;
538 frame = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*frame));
539 frame->Previous = NULL;
540 frame->ActivationContext = actctx;
541 frame->Flags = 0;
542 teb->ActivationContextStack.ActiveFrame = frame;
545 info = (struct startup_info *)(teb + 1);
546 info->teb = teb;
547 info->entry_point = start;
548 info->entry_arg = param;
550 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
551 thread_data->request_fd = request_pipe[1];
552 thread_data->reply_fd = -1;
553 thread_data->wait_fd[0] = -1;
554 thread_data->wait_fd[1] = -1;
556 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
558 pthread_attr_init( &attr );
559 pthread_attr_setstack( &attr, teb->DeallocationStack,
560 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
561 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
562 interlocked_xchg_add( &nb_threads, 1 );
563 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
565 interlocked_xchg_add( &nb_threads, -1 );
566 pthread_attr_destroy( &attr );
567 status = STATUS_NO_MEMORY;
568 goto error;
570 pthread_attr_destroy( &attr );
571 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
573 if (id) id->UniqueThread = ULongToHandle(tid);
574 if (handle_ptr) *handle_ptr = handle;
575 else NtClose( handle );
577 return STATUS_SUCCESS;
579 error:
580 if (teb) signal_free_thread( teb );
581 if (handle) NtClose( handle );
582 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
583 close( request_pipe[1] );
584 return status;
588 /******************************************************************************
589 * RtlGetNtGlobalFlags (NTDLL.@)
591 ULONG WINAPI RtlGetNtGlobalFlags(void)
593 if (!peb) return 0; /* init not done yet */
594 return peb->NtGlobalFlag;
598 /***********************************************************************
599 * NtOpenThread (NTDLL.@)
600 * ZwOpenThread (NTDLL.@)
602 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
603 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
605 NTSTATUS ret;
607 SERVER_START_REQ( open_thread )
609 req->tid = HandleToULong(id->UniqueThread);
610 req->access = access;
611 req->attributes = attr ? attr->Attributes : 0;
612 ret = wine_server_call( req );
613 *handle = wine_server_ptr_handle( reply->handle );
615 SERVER_END_REQ;
616 return ret;
620 /******************************************************************************
621 * NtSuspendThread (NTDLL.@)
622 * ZwSuspendThread (NTDLL.@)
624 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
626 NTSTATUS ret;
628 SERVER_START_REQ( suspend_thread )
630 req->handle = wine_server_obj_handle( handle );
631 if (!(ret = wine_server_call( req ))) *count = reply->count;
633 SERVER_END_REQ;
634 return ret;
638 /******************************************************************************
639 * NtResumeThread (NTDLL.@)
640 * ZwResumeThread (NTDLL.@)
642 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
644 NTSTATUS ret;
646 SERVER_START_REQ( resume_thread )
648 req->handle = wine_server_obj_handle( handle );
649 if (!(ret = wine_server_call( req ))) *count = reply->count;
651 SERVER_END_REQ;
652 return ret;
656 /******************************************************************************
657 * NtAlertResumeThread (NTDLL.@)
658 * ZwAlertResumeThread (NTDLL.@)
660 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
662 FIXME( "stub: should alert thread %p\n", handle );
663 return NtResumeThread( handle, count );
667 /******************************************************************************
668 * NtAlertThread (NTDLL.@)
669 * ZwAlertThread (NTDLL.@)
671 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
673 FIXME( "stub: %p\n", handle );
674 return STATUS_NOT_IMPLEMENTED;
678 /******************************************************************************
679 * NtTerminateThread (NTDLL.@)
680 * ZwTerminateThread (NTDLL.@)
682 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
684 NTSTATUS ret;
685 BOOL self;
687 SERVER_START_REQ( terminate_thread )
689 req->handle = wine_server_obj_handle( handle );
690 req->exit_code = exit_code;
691 ret = wine_server_call( req );
692 self = !ret && reply->self;
694 SERVER_END_REQ;
696 if (self) abort_thread( exit_code );
697 return ret;
701 /******************************************************************************
702 * NtQueueApcThread (NTDLL.@)
704 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
705 ULONG_PTR arg2, ULONG_PTR arg3 )
707 NTSTATUS ret;
708 SERVER_START_REQ( queue_apc )
710 req->handle = wine_server_obj_handle( handle );
711 if (func)
713 req->call.type = APC_USER;
714 req->call.user.func = wine_server_client_ptr( func );
715 req->call.user.args[0] = arg1;
716 req->call.user.args[1] = arg2;
717 req->call.user.args[2] = arg3;
719 else req->call.type = APC_NONE; /* wake up only */
720 ret = wine_server_call( req );
722 SERVER_END_REQ;
723 return ret;
727 /***********************************************************************
728 * NtSetContextThread (NTDLL.@)
729 * ZwSetContextThread (NTDLL.@)
731 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
733 NTSTATUS ret;
734 DWORD dummy, i;
735 BOOL self;
737 #ifdef __i386__
738 /* on i386 debug registers always require a server call */
739 self = (handle == GetCurrentThread());
740 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
742 self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
743 ntdll_get_thread_data()->dr1 == context->Dr1 &&
744 ntdll_get_thread_data()->dr2 == context->Dr2 &&
745 ntdll_get_thread_data()->dr3 == context->Dr3 &&
746 ntdll_get_thread_data()->dr6 == context->Dr6 &&
747 ntdll_get_thread_data()->dr7 == context->Dr7);
749 #else
750 self = FALSE;
751 #endif
753 if (!self)
755 context_t server_context;
757 context_to_server( &server_context, context );
759 SERVER_START_REQ( set_thread_context )
761 req->handle = wine_server_obj_handle( handle );
762 req->suspend = 1;
763 wine_server_add_data( req, &server_context, sizeof(server_context) );
764 ret = wine_server_call( req );
765 self = reply->self;
767 SERVER_END_REQ;
769 if (ret == STATUS_PENDING)
771 for (i = 0; i < 100; i++)
773 SERVER_START_REQ( set_thread_context )
775 req->handle = wine_server_obj_handle( handle );
776 req->suspend = 0;
777 wine_server_add_data( req, &server_context, sizeof(server_context) );
778 ret = wine_server_call( req );
780 SERVER_END_REQ;
781 if (ret == STATUS_PENDING)
783 LARGE_INTEGER timeout;
784 timeout.QuadPart = -10000;
785 NtDelayExecution( FALSE, &timeout );
787 else break;
789 NtResumeThread( handle, &dummy );
790 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
793 if (ret) return ret;
796 if (self) set_cpu_context( context );
797 return STATUS_SUCCESS;
801 /* convert CPU-specific flags to generic server flags */
802 static inline unsigned int get_server_context_flags( DWORD flags )
804 unsigned int ret = 0;
806 flags &= 0x3f; /* mask CPU id flags */
807 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
808 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
809 #ifdef CONTEXT_SEGMENTS
810 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
811 #endif
812 #ifdef CONTEXT_FLOATING_POINT
813 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
814 #endif
815 #ifdef CONTEXT_DEBUG_REGISTERS
816 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
817 #endif
818 #ifdef CONTEXT_EXTENDED_REGISTERS
819 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
820 #endif
821 return ret;
824 /***********************************************************************
825 * NtGetContextThread (NTDLL.@)
826 * ZwGetContextThread (NTDLL.@)
828 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
830 NTSTATUS ret;
831 DWORD dummy, i;
832 DWORD needed_flags = context->ContextFlags;
833 BOOL self = (handle == GetCurrentThread());
835 /* on i386/amd64 debug registers always require a server call */
836 #ifdef __i386__
837 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
838 #elif defined(__x86_64__)
839 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_AMD64)) self = FALSE;
840 #endif
842 if (!self)
844 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
845 context_t server_context;
847 SERVER_START_REQ( get_thread_context )
849 req->handle = wine_server_obj_handle( handle );
850 req->flags = server_flags;
851 req->suspend = 1;
852 wine_server_set_reply( req, &server_context, sizeof(server_context) );
853 ret = wine_server_call( req );
854 self = reply->self;
856 SERVER_END_REQ;
858 if (ret == STATUS_PENDING)
860 for (i = 0; i < 100; i++)
862 SERVER_START_REQ( get_thread_context )
864 req->handle = wine_server_obj_handle( handle );
865 req->flags = server_flags;
866 req->suspend = 0;
867 wine_server_set_reply( req, &server_context, sizeof(server_context) );
868 ret = wine_server_call( req );
870 SERVER_END_REQ;
871 if (ret == STATUS_PENDING)
873 LARGE_INTEGER timeout;
874 timeout.QuadPart = -10000;
875 NtDelayExecution( FALSE, &timeout );
877 else break;
879 NtResumeThread( handle, &dummy );
880 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
882 if (!ret) ret = context_from_server( context, &server_context );
883 if (ret) return ret;
884 needed_flags &= ~context->ContextFlags;
887 if (self)
889 if (needed_flags)
891 CONTEXT ctx;
892 RtlCaptureContext( &ctx );
893 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
894 context->ContextFlags |= ctx.ContextFlags & needed_flags;
896 #ifdef __i386__
897 /* update the cached version of the debug registers */
898 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
900 ntdll_get_thread_data()->dr0 = context->Dr0;
901 ntdll_get_thread_data()->dr1 = context->Dr1;
902 ntdll_get_thread_data()->dr2 = context->Dr2;
903 ntdll_get_thread_data()->dr3 = context->Dr3;
904 ntdll_get_thread_data()->dr6 = context->Dr6;
905 ntdll_get_thread_data()->dr7 = context->Dr7;
907 #endif
909 return STATUS_SUCCESS;
913 /******************************************************************************
914 * NtQueryInformationThread (NTDLL.@)
915 * ZwQueryInformationThread (NTDLL.@)
917 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
918 void *data, ULONG length, ULONG *ret_len )
920 NTSTATUS status;
922 switch(class)
924 case ThreadBasicInformation:
926 THREAD_BASIC_INFORMATION info;
927 const ULONG_PTR affinity_mask = get_system_affinity_mask();
929 SERVER_START_REQ( get_thread_info )
931 req->handle = wine_server_obj_handle( handle );
932 req->tid_in = 0;
933 if (!(status = wine_server_call( req )))
935 info.ExitStatus = reply->exit_code;
936 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
937 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
938 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
939 info.AffinityMask = reply->affinity & affinity_mask;
940 info.Priority = reply->priority;
941 info.BasePriority = reply->priority; /* FIXME */
944 SERVER_END_REQ;
945 if (status == STATUS_SUCCESS)
947 if (data) memcpy( data, &info, min( length, sizeof(info) ));
948 if (ret_len) *ret_len = min( length, sizeof(info) );
951 return status;
952 case ThreadAffinityMask:
954 const ULONG_PTR affinity_mask = get_system_affinity_mask();
955 ULONG_PTR affinity = 0;
957 SERVER_START_REQ( get_thread_info )
959 req->handle = wine_server_obj_handle( handle );
960 req->tid_in = 0;
961 if (!(status = wine_server_call( req )))
962 affinity = reply->affinity & affinity_mask;
964 SERVER_END_REQ;
965 if (status == STATUS_SUCCESS)
967 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
968 if (ret_len) *ret_len = min( length, sizeof(affinity) );
971 return status;
972 case ThreadTimes:
974 KERNEL_USER_TIMES kusrt;
976 SERVER_START_REQ( get_thread_times )
978 req->handle = wine_server_obj_handle( handle );
979 status = wine_server_call( req );
980 if (status == STATUS_SUCCESS)
982 kusrt.CreateTime.QuadPart = reply->creation_time;
983 kusrt.ExitTime.QuadPart = reply->exit_time;
986 SERVER_END_REQ;
987 if (status == STATUS_SUCCESS)
989 /* We call times(2) for kernel time or user time */
990 /* We can only (portably) do this for the current thread */
991 if (handle == GetCurrentThread())
993 struct tms time_buf;
994 long clocks_per_sec = sysconf(_SC_CLK_TCK);
996 times(&time_buf);
997 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
998 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1000 else
1002 static BOOL reported = FALSE;
1004 kusrt.KernelTime.QuadPart = 0;
1005 kusrt.UserTime.QuadPart = 0;
1006 if (reported)
1007 TRACE("Cannot get kerneltime or usertime of other threads\n");
1008 else
1010 FIXME("Cannot get kerneltime or usertime of other threads\n");
1011 reported = TRUE;
1014 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1015 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1018 return status;
1019 case ThreadDescriptorTableEntry:
1021 #ifdef __i386__
1022 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1023 if (length < sizeof(*tdi))
1024 status = STATUS_INFO_LENGTH_MISMATCH;
1025 else if (!(tdi->Selector & 4)) /* GDT selector */
1027 unsigned sel = LOWORD(tdi->Selector) & ~3; /* ignore RPL */
1028 status = STATUS_SUCCESS;
1029 if (!sel) /* null selector */
1030 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1031 else
1033 tdi->Entry.BaseLow = 0;
1034 tdi->Entry.HighWord.Bits.BaseMid = 0;
1035 tdi->Entry.HighWord.Bits.BaseHi = 0;
1036 tdi->Entry.LimitLow = 0xffff;
1037 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1038 tdi->Entry.HighWord.Bits.Dpl = 3;
1039 tdi->Entry.HighWord.Bits.Sys = 0;
1040 tdi->Entry.HighWord.Bits.Pres = 1;
1041 tdi->Entry.HighWord.Bits.Granularity = 1;
1042 tdi->Entry.HighWord.Bits.Default_Big = 1;
1043 tdi->Entry.HighWord.Bits.Type = 0x12;
1044 /* it has to be one of the system GDT selectors */
1045 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1047 if (sel == (wine_get_cs() & ~3))
1048 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1049 else status = STATUS_ACCESS_DENIED;
1053 else
1055 SERVER_START_REQ( get_selector_entry )
1057 req->handle = wine_server_obj_handle( handle );
1058 req->entry = LOWORD(tdi->Selector) >> 3;
1059 status = wine_server_call( req );
1060 if (!status)
1062 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1063 status = STATUS_ACCESS_VIOLATION;
1064 else
1066 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1067 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1068 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1072 SERVER_END_REQ;
1074 if (status == STATUS_SUCCESS && ret_len)
1075 /* yes, that's a bit strange, but it's the way it is */
1076 *ret_len = sizeof(LDT_ENTRY);
1077 #else
1078 status = STATUS_NOT_IMPLEMENTED;
1079 #endif
1080 return status;
1082 case ThreadAmILastThread:
1084 SERVER_START_REQ(get_thread_info)
1086 req->handle = wine_server_obj_handle( handle );
1087 req->tid_in = 0;
1088 status = wine_server_call( req );
1089 if (status == STATUS_SUCCESS)
1091 BOOLEAN last = reply->last;
1092 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1093 if (ret_len) *ret_len = min( length, sizeof(last) );
1096 SERVER_END_REQ;
1097 return status;
1099 case ThreadQuerySetWin32StartAddress:
1101 SERVER_START_REQ( get_thread_info )
1103 req->handle = wine_server_obj_handle( handle );
1104 req->tid_in = 0;
1105 status = wine_server_call( req );
1106 if (status == STATUS_SUCCESS)
1108 PRTL_THREAD_START_ROUTINE entry = wine_server_get_ptr( reply->entry_point );
1109 if (data) memcpy( data, &entry, min( length, sizeof(entry) ) );
1110 if (ret_len) *ret_len = min( length, sizeof(entry) );
1113 SERVER_END_REQ;
1114 return status;
1116 case ThreadGroupInformation:
1118 const ULONG_PTR affinity_mask = get_system_affinity_mask();
1119 GROUP_AFFINITY affinity;
1121 memset(&affinity, 0, sizeof(affinity));
1122 affinity.Group = 0; /* Wine only supports max 64 processors */
1124 SERVER_START_REQ( get_thread_info )
1126 req->handle = wine_server_obj_handle( handle );
1127 req->tid_in = 0;
1128 if (!(status = wine_server_call( req )))
1129 affinity.Mask = reply->affinity & affinity_mask;
1131 SERVER_END_REQ;
1132 if (status == STATUS_SUCCESS)
1134 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
1135 if (ret_len) *ret_len = min( length, sizeof(affinity) );
1138 return status;
1139 case ThreadPriority:
1140 case ThreadBasePriority:
1141 case ThreadImpersonationToken:
1142 case ThreadEnableAlignmentFaultFixup:
1143 case ThreadEventPair_Reusable:
1144 case ThreadZeroTlsCell:
1145 case ThreadPerformanceCount:
1146 case ThreadIdealProcessor:
1147 case ThreadPriorityBoost:
1148 case ThreadSetTlsArrayAddress:
1149 case ThreadIsIoPending:
1150 default:
1151 FIXME( "info class %d not supported yet\n", class );
1152 return STATUS_NOT_IMPLEMENTED;
1157 /******************************************************************************
1158 * NtSetInformationThread (NTDLL.@)
1159 * ZwSetInformationThread (NTDLL.@)
1161 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1162 LPCVOID data, ULONG length )
1164 NTSTATUS status;
1165 switch(class)
1167 case ThreadZeroTlsCell:
1168 if (handle == GetCurrentThread())
1170 LIST_ENTRY *entry;
1171 DWORD index;
1173 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1174 index = *(const DWORD *)data;
1175 if (index < TLS_MINIMUM_AVAILABLE)
1177 RtlAcquirePebLock();
1178 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1180 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1181 teb->TlsSlots[index] = 0;
1183 RtlReleasePebLock();
1185 else
1187 index -= TLS_MINIMUM_AVAILABLE;
1188 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1189 return STATUS_INVALID_PARAMETER;
1190 RtlAcquirePebLock();
1191 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1193 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1194 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1196 RtlReleasePebLock();
1198 return STATUS_SUCCESS;
1200 FIXME( "ZeroTlsCell not supported on other threads\n" );
1201 return STATUS_NOT_IMPLEMENTED;
1203 case ThreadImpersonationToken:
1205 const HANDLE *phToken = data;
1206 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1207 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1208 SERVER_START_REQ( set_thread_info )
1210 req->handle = wine_server_obj_handle( handle );
1211 req->token = wine_server_obj_handle( *phToken );
1212 req->mask = SET_THREAD_INFO_TOKEN;
1213 status = wine_server_call( req );
1215 SERVER_END_REQ;
1217 return status;
1218 case ThreadBasePriority:
1220 const DWORD *pprio = data;
1221 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1222 SERVER_START_REQ( set_thread_info )
1224 req->handle = wine_server_obj_handle( handle );
1225 req->priority = *pprio;
1226 req->mask = SET_THREAD_INFO_PRIORITY;
1227 status = wine_server_call( req );
1229 SERVER_END_REQ;
1231 return status;
1232 case ThreadAffinityMask:
1234 const ULONG_PTR affinity_mask = get_system_affinity_mask();
1235 ULONG_PTR req_aff;
1237 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1238 req_aff = *(const ULONG_PTR *)data;
1239 if ((ULONG)req_aff == ~0u) req_aff = affinity_mask;
1240 else if (req_aff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1241 else if (!req_aff) return STATUS_INVALID_PARAMETER;
1242 SERVER_START_REQ( set_thread_info )
1244 req->handle = wine_server_obj_handle( handle );
1245 req->affinity = req_aff;
1246 req->mask = SET_THREAD_INFO_AFFINITY;
1247 status = wine_server_call( req );
1249 SERVER_END_REQ;
1251 return status;
1252 case ThreadHideFromDebugger:
1253 /* pretend the call succeeded to satisfy some code protectors */
1254 return STATUS_SUCCESS;
1255 case ThreadQuerySetWin32StartAddress:
1257 const PRTL_THREAD_START_ROUTINE *entry = data;
1258 if (length != sizeof(PRTL_THREAD_START_ROUTINE)) return STATUS_INVALID_PARAMETER;
1259 SERVER_START_REQ( set_thread_info )
1261 req->handle = wine_server_obj_handle( handle );
1262 req->mask = SET_THREAD_INFO_ENTRYPOINT;
1263 req->entry_point = wine_server_client_ptr( *entry );
1264 status = wine_server_call( req );
1266 SERVER_END_REQ;
1268 return status;
1269 case ThreadGroupInformation:
1271 const ULONG_PTR affinity_mask = get_system_affinity_mask();
1272 const GROUP_AFFINITY *req_aff;
1274 if (length != sizeof(*req_aff)) return STATUS_INVALID_PARAMETER;
1275 if (!data) return STATUS_ACCESS_VIOLATION;
1276 req_aff = data;
1278 /* On Windows the request fails if the reserved fields are set */
1279 if (req_aff->Reserved[0] || req_aff->Reserved[1] || req_aff->Reserved[2])
1280 return STATUS_INVALID_PARAMETER;
1282 /* Wine only supports max 64 processors */
1283 if (req_aff->Group) return STATUS_INVALID_PARAMETER;
1284 if (req_aff->Mask & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1285 if (!req_aff->Mask) return STATUS_INVALID_PARAMETER;
1286 SERVER_START_REQ( set_thread_info )
1288 req->handle = wine_server_obj_handle( handle );
1289 req->affinity = req_aff->Mask;
1290 req->mask = SET_THREAD_INFO_AFFINITY;
1291 status = wine_server_call( req );
1293 SERVER_END_REQ;
1295 return status;
1296 case ThreadBasicInformation:
1297 case ThreadTimes:
1298 case ThreadPriority:
1299 case ThreadDescriptorTableEntry:
1300 case ThreadEnableAlignmentFaultFixup:
1301 case ThreadEventPair_Reusable:
1302 case ThreadPerformanceCount:
1303 case ThreadAmILastThread:
1304 case ThreadIdealProcessor:
1305 case ThreadPriorityBoost:
1306 case ThreadSetTlsArrayAddress:
1307 case ThreadIsIoPending:
1308 default:
1309 FIXME( "info class %d not supported yet\n", class );
1310 return STATUS_NOT_IMPLEMENTED;
1314 /******************************************************************************
1315 * NtGetCurrentProcessorNumber (NTDLL.@)
1317 * Return the processor, on which the thread is running
1320 ULONG WINAPI NtGetCurrentProcessorNumber(void)
1322 ULONG processor;
1324 #if defined(__linux__) && defined(__NR_getcpu)
1325 int res = syscall(__NR_getcpu, &processor, NULL, NULL);
1326 if (res != -1) return processor;
1327 #endif
1329 if (NtCurrentTeb()->Peb->NumberOfProcessors > 1)
1331 ULONG_PTR thread_mask, processor_mask;
1332 NTSTATUS status;
1334 status = NtQueryInformationThread(GetCurrentThread(), ThreadAffinityMask,
1335 &thread_mask, sizeof(thread_mask), NULL);
1336 if (status == STATUS_SUCCESS)
1338 for (processor = 0; processor < NtCurrentTeb()->Peb->NumberOfProcessors; processor++)
1340 processor_mask = (1 << processor);
1341 if (thread_mask & processor_mask)
1343 if (thread_mask != processor_mask)
1344 FIXME("need multicore support (%d processors)\n",
1345 NtCurrentTeb()->Peb->NumberOfProcessors);
1346 return processor;
1352 /* fallback to the first processor */
1353 return 0;