1 /*
2 * NT threads support
3 *
4 * Copyright 1996, 2003 Alexandre Julliard
5 *
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.
10 *
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.
15 *
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
19 */
20
21 #include "config.h"
22 #include "wine/port.h"
23
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
36
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"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(thread);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50
51 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
52
53 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
54
55 /* info passed to a starting thread */
56 struct startup_info
57 {
58 TEB *teb;
59 PRTL_THREAD_START_ROUTINE entry_point;
60 void *entry_arg;
61 };
62
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 LIST_ENTRY tls_links;
71 static int nb_threads = 1;
72
73 /***********************************************************************
74 * get_unicode_string
75 *
76 * Copy a unicode string from the startup info.
77 */
78 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
79 {
80 str->Buffer = *dst;
81 str->Length = len;
82 str->MaximumLength = len + sizeof(WCHAR);
83 memcpy( str->Buffer, *src, len );
84 str->Buffer[len / sizeof(WCHAR)] = 0;
85 *src += len / sizeof(WCHAR);
86 *dst += len / sizeof(WCHAR) + 1;
87 }
88
89 /***********************************************************************
90 * init_user_process_params
91 *
92 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
93 */
94 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
95 {
96 void *ptr;
97 WCHAR *src, *dst;
98 SIZE_T info_size, env_size, size, alloc_size;
99 NTSTATUS status;
100 startup_info_t *info;
101 RTL_USER_PROCESS_PARAMETERS *params = NULL;
102
103 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
104 return STATUS_NO_MEMORY;
105
106 SERVER_START_REQ( get_startup_info )
107 {
108 wine_server_set_reply( req, info, data_size );
109 if (!(status = wine_server_call( req )))
110 {
111 data_size = wine_server_reply_size( reply );
112 info_size = reply->info_size;
113 env_size = data_size - info_size;
114 *exe_file = wine_server_ptr_handle( reply->exe_file );
115 }
116 }
117 SERVER_END_REQ;
118 if (status != STATUS_SUCCESS) goto done;
119
120 size = sizeof(*params);
121 size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
122 size += info->dllpath_len + sizeof(WCHAR);
123 size += info->imagepath_len + sizeof(WCHAR);
124 size += info->cmdline_len + sizeof(WCHAR);
125 size += info->title_len + sizeof(WCHAR);
126 size += info->desktop_len + sizeof(WCHAR);
127 size += info->shellinfo_len + sizeof(WCHAR);
128 size += info->runtime_len + sizeof(WCHAR);
129
130 alloc_size = size;
131 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &alloc_size,
132 MEM_COMMIT, PAGE_READWRITE );
133 if (status != STATUS_SUCCESS) goto done;
134
135 NtCurrentTeb()->Peb->ProcessParameters = params;
136 params->AllocationSize = alloc_size;
137 params->Size = size;
138 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
139 params->DebugFlags = info->debug_flags;
140 params->ConsoleHandle = wine_server_ptr_handle( info->console );
141 params->ConsoleFlags = info->console_flags;
142 params->hStdInput = wine_server_ptr_handle( info->hstdin );
143 params->hStdOutput = wine_server_ptr_handle( info->hstdout );
144 params->hStdError = wine_server_ptr_handle( info->hstderr );
145 params->dwX = info->x;
146 params->dwY = info->y;
147 params->dwXSize = info->xsize;
148 params->dwYSize = info->ysize;
149 params->dwXCountChars = info->xchars;
150 params->dwYCountChars = info->ychars;
151 params->dwFillAttribute = info->attribute;
152 params->dwFlags = info->flags;
153 params->wShowWindow = info->show;
154
155 src = (WCHAR *)(info + 1);
156 dst = (WCHAR *)(params + 1);
157
158 /* current directory needs more space */
159 get_unicode_string( ¶ms->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
160 params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
161 dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
162
163 get_unicode_string( ¶ms->DllPath, &src, &dst, info->dllpath_len );
164 get_unicode_string( ¶ms->ImagePathName, &src, &dst, info->imagepath_len );
165 get_unicode_string( ¶ms->CommandLine, &src, &dst, info->cmdline_len );
166 get_unicode_string( ¶ms->WindowTitle, &src, &dst, info->title_len );
167 get_unicode_string( ¶ms->Desktop, &src, &dst, info->desktop_len );
168 get_unicode_string( ¶ms->ShellInfo, &src, &dst, info->shellinfo_len );
169
170 /* runtime info isn't a real string */
171 params->RuntimeInfo.Buffer = dst;
172 params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
173 memcpy( dst, src, info->runtime_len );
174
175 /* environment needs to be a separate memory block */
176 ptr = NULL;
177 alloc_size = max( 1, env_size );
178 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
179 MEM_COMMIT, PAGE_READWRITE );
180 if (status != STATUS_SUCCESS) goto done;
181 memcpy( ptr, (char *)info + info_size, env_size );
182 params->Environment = ptr;
183
184 done:
185 RtlFreeHeap( GetProcessHeap(), 0, info );
186 return status;
187 }
188
189 /***********************************************************************
190 * thread_init
191 *
192 * Setup the initial thread.
193 *
194 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
195 */
196 HANDLE thread_init(void)
197 {
198 TEB *teb;
199 void *addr;
200 SIZE_T size, info_size;
201 HANDLE exe_file = 0;
202 LARGE_INTEGER now;
203 NTSTATUS status;
204 struct ntdll_thread_data *thread_data;
205 static struct debug_info debug_info; /* debug info for initial thread */
206
207 virtual_init();
208
209 /* reserve space for shared user data */
210
211 addr = (void *)0x7ffe0000;
212 size = 0x10000;
213 status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
214 MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
215 if (status)
216 {
217 MESSAGE( "wine: failed to map the shared user data: %08x\n", status );
218 exit(1);
219 }
220 user_shared_data = addr;
221
222 /* allocate and initialize the PEB */
223
224 addr = NULL;
225 size = sizeof(*peb);
226 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
227 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
228 peb = addr;
229
230 peb->ProcessParameters = ¶ms;
231 peb->TlsBitmap = &tls_bitmap;
232 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
233 peb->FlsBitmap = &fls_bitmap;
234 peb->LdrData = &ldr;
235 params.CurrentDirectory.DosPath.Buffer = current_dir;
236 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
237 params.wShowWindow = 1; /* SW_SHOWNORMAL */
238 ldr.Length = sizeof(ldr);
239 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
240 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
241 sizeof(peb->TlsExpansionBitmapBits) * 8 );
242 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
243 InitializeListHead( &peb->FlsListHead );
244 InitializeListHead( &ldr.InLoadOrderModuleList );
245 InitializeListHead( &ldr.InMemoryOrderModuleList );
246 InitializeListHead( &ldr.InInitializationOrderModuleList );
247 InitializeListHead( &tls_links );
248
249 /* allocate and initialize the initial TEB */
250
251 signal_alloc_thread( &teb );
252 teb->Peb = peb;
253 teb->Tib.StackBase = (void *)~0UL;
254 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
255 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
256
257 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
258 thread_data->request_fd = -1;
259 thread_data->reply_fd = -1;
260 thread_data->wait_fd[0] = -1;
261 thread_data->wait_fd[1] = -1;
262 thread_data->debug_info = &debug_info;
263 InsertHeadList( &tls_links, &teb->TlsLinks );
264
265 signal_init_thread( teb );
266 virtual_init_threading();
267
268 debug_info.str_pos = debug_info.strings;
269 debug_info.out_pos = debug_info.output;
270 debug_init();
271
272 /* setup the server connection */
273 server_init_process();
274 info_size = server_init_thread( peb );
275
276 /* create the process heap */
277 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
278 {
279 MESSAGE( "wine: failed to create the process heap\n" );
280 exit(1);
281 }
282
283 /* allocate user parameters */
284 if (info_size)
285 {
286 init_user_process_params( info_size, &exe_file );
287 }
288 else
289 {
290 if (isatty(0) || isatty(1) || isatty(2))
291 params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
292 if (!isatty(0))
293 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
294 if (!isatty(1))
295 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
296 if (!isatty(2))
297 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
298 }
299
300 /* initialize time values in user_shared_data */
301 NtQuerySystemTime( &now );
302 user_shared_data->SystemTime.LowPart = now.u.LowPart;
303 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
304 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
305 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
306 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
307 user_shared_data->TickCountMultiplier = 1 << 24;
308
309 fill_cpu_info();
310
311 return exe_file;
312 }
313
314
315 /***********************************************************************
316 * terminate_thread
317 */
318 void terminate_thread( int status )
319 {
320 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
321 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
322
323 close( ntdll_get_thread_data()->wait_fd[0] );
324 close( ntdll_get_thread_data()->wait_fd[1] );
325 close( ntdll_get_thread_data()->reply_fd );
326 close( ntdll_get_thread_data()->request_fd );
327 pthread_exit( UIntToPtr(status) );
328 }
329
330
331 /***********************************************************************
332 * exit_thread
333 */
334 void exit_thread( int status )
335 {
336 static void *prev_teb;
337 TEB *teb;
338
339 if (status) /* send the exit code to the server (0 is already the default) */
340 {
341 SERVER_START_REQ( terminate_thread )
342 {
343 req->handle = wine_server_obj_handle( GetCurrentThread() );
344 req->exit_code = status;
345 wine_server_call( req );
346 }
347 SERVER_END_REQ;
348 }
349
350 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
351 {
352 LdrShutdownProcess();
353 exit( status );
354 }
355
356 LdrShutdownThread();
357 RtlAcquirePebLock();
358 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
359 RtlReleasePebLock();
360 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
361 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
362
363 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
364
365 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
366 {
367 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
368
369 if (thread_data->pthread_id)
370 {
371 pthread_join( thread_data->pthread_id, NULL );
372 signal_free_thread( teb );
373 }
374 }
375
376 close( ntdll_get_thread_data()->wait_fd[0] );
377 close( ntdll_get_thread_data()->wait_fd[1] );
378 close( ntdll_get_thread_data()->reply_fd );
379 close( ntdll_get_thread_data()->request_fd );
380 pthread_exit( UIntToPtr(status) );
381 }
382
383
384 /***********************************************************************
385 * start_thread
386 *
387 * Startup routine for a newly created thread.
388 */
389 static void start_thread( struct startup_info *info )
390 {
391 TEB *teb = info->teb;
392 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
393 PRTL_THREAD_START_ROUTINE func = info->entry_point;
394 void *arg = info->entry_arg;
395 struct debug_info debug_info;
396
397 debug_info.str_pos = debug_info.strings;
398 debug_info.out_pos = debug_info.output;
399 thread_data->debug_info = &debug_info;
400 thread_data->pthread_id = pthread_self();
401
402 signal_init_thread( teb );
403 server_init_thread( func );
404 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
405
406 RtlAcquirePebLock();
407 InsertHeadList( &tls_links, &teb->TlsLinks );
408 RtlReleasePebLock();
409
410 MODULE_DllThreadAttach( NULL );
411
412 if (TRACE_ON(relay))
413 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
414
415 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
416 }
417
418
419 /***********************************************************************
420 * RtlCreateUserThread (NTDLL.@)
421 */
422 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
423 BOOLEAN suspended, PVOID stack_addr,
424 SIZE_T stack_reserve, SIZE_T stack_commit,
425 PRTL_THREAD_START_ROUTINE start, void *param,
426 HANDLE *handle_ptr, CLIENT_ID *id )
427 {
428 sigset_t sigset;
429 pthread_t pthread_id;
430 pthread_attr_t attr;
431 struct ntdll_thread_data *thread_data;
432 struct startup_info *info = NULL;
433 HANDLE handle = 0;
434 TEB *teb = NULL;
435 DWORD tid = 0;
436 int request_pipe[2];
437 NTSTATUS status;
438
439 if (process != NtCurrentProcess())
440 {
441 apc_call_t call;
442 apc_result_t result;
443
444 memset( &call, 0, sizeof(call) );
445
446 call.create_thread.type = APC_CREATE_THREAD;
447 call.create_thread.func = wine_server_client_ptr( start );
448 call.create_thread.arg = wine_server_client_ptr( param );
449 call.create_thread.reserve = stack_reserve;
450 call.create_thread.commit = stack_commit;
451 call.create_thread.suspend = suspended;
452 status = NTDLL_queue_process_apc( process, &call, &result );
453 if (status != STATUS_SUCCESS) return status;
454
455 if (result.create_thread.status == STATUS_SUCCESS)
456 {
457 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
458 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
459 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
460 }
461 return result.create_thread.status;
462 }
463
464 if (RtlDllShutdownInProgress()) return STATUS_ACCESS_DENIED;
465
466 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
467 wine_server_send_fd( request_pipe[0] );
468
469 SERVER_START_REQ( new_thread )
470 {
471 req->access = THREAD_ALL_ACCESS;
472 req->attributes = 0; /* FIXME */
473 req->suspend = suspended;
474 req->request_fd = request_pipe[0];
475 if (!(status = wine_server_call( req )))
476 {
477 handle = wine_server_ptr_handle( reply->handle );
478 tid = reply->tid;
479 }
480 close( request_pipe[0] );
481 }
482 SERVER_END_REQ;
483
484 if (status)
485 {
486 close( request_pipe[1] );
487 return status;
488 }
489
490 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
491
492 if ((status = signal_alloc_thread( &teb ))) goto error;
493
494 teb->Peb = NtCurrentTeb()->Peb;
495 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
496 teb->ClientId.UniqueThread = ULongToHandle(tid);
497 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
498 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
499
500 info = (struct startup_info *)(teb + 1);
501 info->teb = teb;
502 info->entry_point = start;
503 info->entry_arg = param;
504
505 thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
506 thread_data->request_fd = request_pipe[1];
507 thread_data->reply_fd = -1;
508 thread_data->wait_fd[0] = -1;
509 thread_data->wait_fd[1] = -1;
510
511 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
512
513 pthread_attr_init( &attr );
514 pthread_attr_setstack( &attr, teb->DeallocationStack,
515 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
516 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
517 interlocked_xchg_add( &nb_threads, 1 );
518 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
519 {
520 interlocked_xchg_add( &nb_threads, -1 );
521 pthread_attr_destroy( &attr );
522 status = STATUS_NO_MEMORY;
523 goto error;
524 }
525 pthread_attr_destroy( &attr );
526 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
527
528 if (id) id->UniqueThread = ULongToHandle(tid);
529 if (handle_ptr) *handle_ptr = handle;
530 else NtClose( handle );
531
532 return STATUS_SUCCESS;
533
534 error:
535 if (teb) signal_free_thread( teb );
536 if (handle) NtClose( handle );
537 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
538 close( request_pipe[1] );
539 return status;
540 }
541
542
543 /******************************************************************************
544 * RtlGetNtGlobalFlags (NTDLL.@)
545 */
546 ULONG WINAPI RtlGetNtGlobalFlags(void)
547 {
548 if (!peb) return 0; /* init not done yet */
549 return peb->NtGlobalFlag;
550 }
551
552
553 /***********************************************************************
554 * NtOpenThread (NTDLL.@)
555 * ZwOpenThread (NTDLL.@)
556 */
557 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
558 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
559 {
560 NTSTATUS ret;
561
562 SERVER_START_REQ( open_thread )
563 {
564 req->tid = HandleToULong(id->UniqueThread);
565 req->access = access;
566 req->attributes = attr ? attr->Attributes : 0;
567 ret = wine_server_call( req );
568 *handle = wine_server_ptr_handle( reply->handle );
569 }
570 SERVER_END_REQ;
571 return ret;
572 }
573
574
575 /******************************************************************************
576 * NtSuspendThread (NTDLL.@)
577 * ZwSuspendThread (NTDLL.@)
578 */
579 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
580 {
581 NTSTATUS ret;
582
583 SERVER_START_REQ( suspend_thread )
584 {
585 req->handle = wine_server_obj_handle( handle );
586 if (!(ret = wine_server_call( req ))) *count = reply->count;
587 }
588 SERVER_END_REQ;
589 return ret;
590 }
591
592
593 /******************************************************************************
594 * NtResumeThread (NTDLL.@)
595 * ZwResumeThread (NTDLL.@)
596 */
597 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
598 {
599 NTSTATUS ret;
600
601 SERVER_START_REQ( resume_thread )
602 {
603 req->handle = wine_server_obj_handle( handle );
604 if (!(ret = wine_server_call( req ))) *count = reply->count;
605 }
606 SERVER_END_REQ;
607 return ret;
608 }
609
610
611 /******************************************************************************
612 * NtAlertResumeThread (NTDLL.@)
613 * ZwAlertResumeThread (NTDLL.@)
614 */
615 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
616 {
617 FIXME( "stub: should alert thread %p\n", handle );
618 return NtResumeThread( handle, count );
619 }
620
621
622 /******************************************************************************
623 * NtAlertThread (NTDLL.@)
624 * ZwAlertThread (NTDLL.@)
625 */
626 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
627 {
628 FIXME( "stub: %p\n", handle );
629 return STATUS_NOT_IMPLEMENTED;
630 }
631
632
633 /******************************************************************************
634 * NtTerminateThread (NTDLL.@)
635 * ZwTerminateThread (NTDLL.@)
636 */
637 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
638 {
639 NTSTATUS ret;
640 BOOL self;
641
642 SERVER_START_REQ( terminate_thread )
643 {
644 req->handle = wine_server_obj_handle( handle );
645 req->exit_code = exit_code;
646 ret = wine_server_call( req );
647 self = !ret && reply->self;
648 }
649 SERVER_END_REQ;
650
651 if (self) abort_thread( exit_code );
652 return ret;
653 }
654
655
656 /******************************************************************************
657 * NtQueueApcThread (NTDLL.@)
658 */
659 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
660 ULONG_PTR arg2, ULONG_PTR arg3 )
661 {
662 NTSTATUS ret;
663 SERVER_START_REQ( queue_apc )
664 {
665 req->handle = wine_server_obj_handle( handle );
666 if (func)
667 {
668 req->call.type = APC_USER;
669 req->call.user.func = wine_server_client_ptr( func );
670 req->call.user.args[0] = arg1;
671 req->call.user.args[1] = arg2;
672 req->call.user.args[2] = arg3;
673 }
674 else req->call.type = APC_NONE; /* wake up only */
675 ret = wine_server_call( req );
676 }
677 SERVER_END_REQ;
678 return ret;
679 }
680
681
682 /***********************************************************************
683 * NtSetContextThread (NTDLL.@)
684 * ZwSetContextThread (NTDLL.@)
685 */
686 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
687 {
688 NTSTATUS ret;
689 DWORD dummy, i;
690 BOOL self = FALSE;
691
692 #ifdef __i386__
693 /* on i386 debug registers always require a server call */
694 self = (handle == GetCurrentThread());
695 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
696 {
697 self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
698 ntdll_get_thread_data()->dr1 == context->Dr1 &&
699 ntdll_get_thread_data()->dr2 == context->Dr2 &&
700 ntdll_get_thread_data()->dr3 == context->Dr3 &&
701 ntdll_get_thread_data()->dr6 == context->Dr6 &&
702 ntdll_get_thread_data()->dr7 == context->Dr7);
703 }
704 #endif
705
706 if (!self)
707 {
708 context_t server_context;
709
710 context_to_server( &server_context, context );
711
712 SERVER_START_REQ( set_thread_context )
713 {
714 req->handle = wine_server_obj_handle( handle );
715 req->suspend = 1;
716 wine_server_add_data( req, &server_context, sizeof(server_context) );
717 ret = wine_server_call( req );
718 self = reply->self;
719 }
720 SERVER_END_REQ;
721
722 if (ret == STATUS_PENDING)
723 {
724 for (i = 0; i < 100; i++)
725 {
726 SERVER_START_REQ( set_thread_context )
727 {
728 req->handle = wine_server_obj_handle( handle );
729 req->suspend = 0;
730 wine_server_add_data( req, &server_context, sizeof(server_context) );
731 ret = wine_server_call( req );
732 }
733 SERVER_END_REQ;
734 if (ret == STATUS_PENDING)
735 {
736 LARGE_INTEGER timeout;
737 timeout.QuadPart = -10000;
738 NtDelayExecution( FALSE, &timeout );
739 }
740 else break;
741 }
742 NtResumeThread( handle, &dummy );
743 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
744 }
745
746 if (ret) return ret;
747 }
748
749 if (self) set_cpu_context( context );
750 return STATUS_SUCCESS;
751 }
752
753
754 /* convert CPU-specific flags to generic server flags */
755 static inline unsigned int get_server_context_flags( DWORD flags )
756 {
757 unsigned int ret = 0;
758
759 flags &= 0x3f; /* mask CPU id flags */
760 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
761 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
762 #ifdef CONTEXT_SEGMENTS
763 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
764 #endif
765 #ifdef CONTEXT_FLOATING_POINT
766 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
767 #endif
768 #ifdef CONTEXT_DEBUG_REGISTERS
769 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
770 #endif
771 #ifdef CONTEXT_EXTENDED_REGISTERS
772 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
773 #endif
774 return ret;
775 }
776
777 /***********************************************************************
778 * NtGetContextThread (NTDLL.@)
779 * ZwGetContextThread (NTDLL.@)
780 */
781 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
782 {
783 NTSTATUS ret;
784 DWORD dummy, i;
785 DWORD needed_flags = context->ContextFlags;
786 BOOL self = (handle == GetCurrentThread());
787
788 #ifdef __i386__
789 /* on i386 debug registers always require a server call */
790 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
791 #endif
792
793 if (!self)
794 {
795 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
796 context_t server_context;
797
798 SERVER_START_REQ( get_thread_context )
799 {
800 req->handle = wine_server_obj_handle( handle );
801 req->flags = server_flags;
802 req->suspend = 1;
803 wine_server_set_reply( req, &server_context, sizeof(server_context) );
804 ret = wine_server_call( req );
805 self = reply->self;
806 }
807 SERVER_END_REQ;
808
809 if (ret == STATUS_PENDING)
810 {
811 for (i = 0; i < 100; i++)
812 {
813 SERVER_START_REQ( get_thread_context )
814 {
815 req->handle = wine_server_obj_handle( handle );
816 req->flags = server_flags;
817 req->suspend = 0;
818 wine_server_set_reply( req, &server_context, sizeof(server_context) );
819 ret = wine_server_call( req );
820 }
821 SERVER_END_REQ;
822 if (ret == STATUS_PENDING)
823 {
824 LARGE_INTEGER timeout;
825 timeout.QuadPart = -10000;
826 NtDelayExecution( FALSE, &timeout );
827 }
828 else break;
829 }
830 NtResumeThread( handle, &dummy );
831 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
832 }
833 if (!ret) ret = context_from_server( context, &server_context );
834 if (ret) return ret;
835 needed_flags &= ~context->ContextFlags;
836 }
837
838 if (self)
839 {
840 if (needed_flags)
841 {
842 CONTEXT ctx;
843 RtlCaptureContext( &ctx );
844 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
845 context->ContextFlags |= ctx.ContextFlags & needed_flags;
846 }
847 #ifdef __i386__
848 /* update the cached version of the debug registers */
849 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
850 {
851 ntdll_get_thread_data()->dr0 = context->Dr0;
852 ntdll_get_thread_data()->dr1 = context->Dr1;
853 ntdll_get_thread_data()->dr2 = context->Dr2;
854 ntdll_get_thread_data()->dr3 = context->Dr3;
855 ntdll_get_thread_data()->dr6 = context->Dr6;
856 ntdll_get_thread_data()->dr7 = context->Dr7;
857 }
858 #endif
859 }
860 return STATUS_SUCCESS;
861 }
862
863
864 /******************************************************************************
865 * NtQueryInformationThread (NTDLL.@)
866 * ZwQueryInformationThread (NTDLL.@)
867 */
868 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
869 void *data, ULONG length, ULONG *ret_len )
870 {
871 NTSTATUS status;
872
873 switch(class)
874 {
875 case ThreadBasicInformation:
876 {
877 THREAD_BASIC_INFORMATION info;
878 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
879
880 SERVER_START_REQ( get_thread_info )
881 {
882 req->handle = wine_server_obj_handle( handle );
883 req->tid_in = 0;
884 if (!(status = wine_server_call( req )))
885 {
886 info.ExitStatus = reply->exit_code;
887 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
888 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
889 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
890 info.AffinityMask = reply->affinity & affinity_mask;
891 info.Priority = reply->priority;
892 info.BasePriority = reply->priority; /* FIXME */
893 }
894 }
895 SERVER_END_REQ;
896 if (status == STATUS_SUCCESS)
897 {
898 if (data) memcpy( data, &info, min( length, sizeof(info) ));
899 if (ret_len) *ret_len = min( length, sizeof(info) );
900 }
901 }
902 return status;
903 case ThreadAffinityMask:
904 {
905 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
906 ULONG_PTR affinity = 0;
907
908 SERVER_START_REQ( get_thread_info )
909 {
910 req->handle = wine_server_obj_handle( handle );
911 req->tid_in = 0;
912 if (!(status = wine_server_call( req )))
913 affinity = reply->affinity & affinity_mask;
914 }
915 SERVER_END_REQ;
916 if (status == STATUS_SUCCESS)
917 {
918 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
919 if (ret_len) *ret_len = min( length, sizeof(affinity) );
920 }
921 }
922 return status;
923 case ThreadTimes:
924 {
925 KERNEL_USER_TIMES kusrt;
926 /* We need to do a server call to get the creation time or exit time */
927 /* This works on any thread */
928 SERVER_START_REQ( get_thread_info )
929 {
930 req->handle = wine_server_obj_handle( handle );
931 req->tid_in = 0;
932 status = wine_server_call( req );
933 if (status == STATUS_SUCCESS)
934 {
935 kusrt.CreateTime.QuadPart = reply->creation_time;
936 kusrt.ExitTime.QuadPart = reply->exit_time;
937 }
938 }
939 SERVER_END_REQ;
940 if (status == STATUS_SUCCESS)
941 {
942 /* We call times(2) for kernel time or user time */
943 /* We can only (portably) do this for the current thread */
944 if (handle == GetCurrentThread())
945 {
946 struct tms time_buf;
947 long clocks_per_sec = sysconf(_SC_CLK_TCK);
948
949 times(&time_buf);
950 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
951 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
952 }
953 else
954 {
955 static BOOL reported = FALSE;
956
957 kusrt.KernelTime.QuadPart = 0;
958 kusrt.UserTime.QuadPart = 0;
959 if (reported)
960 TRACE("Cannot get kerneltime or usertime of other threads\n");
961 else
962 {
963 FIXME("Cannot get kerneltime or usertime of other threads\n");
964 reported = TRUE;
965 }
966 }
967 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
968 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
969 }
970 }
971 return status;
972 case ThreadDescriptorTableEntry:
973 {
974 #ifdef __i386__
975 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
976 if (length < sizeof(*tdi))
977 status = STATUS_INFO_LENGTH_MISMATCH;
978 else if (!(tdi->Selector & 4)) /* GDT selector */
979 {
980 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
981 status = STATUS_SUCCESS;
982 if (!sel) /* null selector */
983 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
984 else
985 {
986 tdi->Entry.BaseLow = 0;
987 tdi->Entry.HighWord.Bits.BaseMid = 0;
988 tdi->Entry.HighWord.Bits.BaseHi = 0;
989 tdi->Entry.LimitLow = 0xffff;
990 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
991 tdi->Entry.HighWord.Bits.Dpl = 3;
992 tdi->Entry.HighWord.Bits.Sys = 0;
993 tdi->Entry.HighWord.Bits.Pres = 1;
994 tdi->Entry.HighWord.Bits.Granularity = 1;
995 tdi->Entry.HighWord.Bits.Default_Big = 1;
996 tdi->Entry.HighWord.Bits.Type = 0x12;
997 /* it has to be one of the system GDT selectors */
998 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
999 {
1000 if (sel == (wine_get_cs() & ~3))
1001 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1002 else status = STATUS_ACCESS_DENIED;
1003 }
1004 }
1005 }
1006 else
1007 {
1008 SERVER_START_REQ( get_selector_entry )
1009 {
1010 req->handle = wine_server_obj_handle( handle );
1011 req->entry = tdi->Selector >> 3;
1012 status = wine_server_call( req );
1013 if (!status)
1014 {
1015 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1016 status = STATUS_ACCESS_VIOLATION;
1017 else
1018 {
1019 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1020 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1021 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1022 }
1023 }
1024 }
1025 SERVER_END_REQ;
1026 }
1027 if (status == STATUS_SUCCESS && ret_len)
1028 /* yes, that's a bit strange, but it's the way it is */
1029 *ret_len = sizeof(LDT_ENTRY);
1030 #else
1031 status = STATUS_NOT_IMPLEMENTED;
1032 #endif
1033 return status;
1034 }
1035 case ThreadAmILastThread:
1036 {
1037 SERVER_START_REQ(get_thread_info)
1038 {
1039 req->handle = wine_server_obj_handle( handle );
1040 req->tid_in = 0;
1041 status = wine_server_call( req );
1042 if (status == STATUS_SUCCESS)
1043 {
1044 BOOLEAN last = reply->last;
1045 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1046 if (ret_len) *ret_len = min( length, sizeof(last) );
1047 }
1048 }
1049 SERVER_END_REQ;
1050 return status;
1051 }
1052 case ThreadPriority:
1053 case ThreadBasePriority:
1054 case ThreadImpersonationToken:
1055 case ThreadEnableAlignmentFaultFixup:
1056 case ThreadEventPair_Reusable:
1057 case ThreadQuerySetWin32StartAddress:
1058 case ThreadZeroTlsCell:
1059 case ThreadPerformanceCount:
1060 case ThreadIdealProcessor:
1061 case ThreadPriorityBoost:
1062 case ThreadSetTlsArrayAddress:
1063 case ThreadIsIoPending:
1064 default:
1065 FIXME( "info class %d not supported yet\n", class );
1066 return STATUS_NOT_IMPLEMENTED;
1067 }
1068 }
1069
1070
1071 /******************************************************************************
1072 * NtSetInformationThread (NTDLL.@)
1073 * ZwSetInformationThread (NTDLL.@)
1074 */
1075 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1076 LPCVOID data, ULONG length )
1077 {
1078 NTSTATUS status;
1079 switch(class)
1080 {
1081 case ThreadZeroTlsCell:
1082 if (handle == GetCurrentThread())
1083 {
1084 LIST_ENTRY *entry;
1085 DWORD index;
1086
1087 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1088 index = *(const DWORD *)data;
1089 if (index < TLS_MINIMUM_AVAILABLE)
1090 {
1091 RtlAcquirePebLock();
1092 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1093 {
1094 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1095 teb->TlsSlots[index] = 0;
1096 }
1097 RtlReleasePebLock();
1098 }
1099 else
1100 {
1101 index -= TLS_MINIMUM_AVAILABLE;
1102 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1103 return STATUS_INVALID_PARAMETER;
1104 RtlAcquirePebLock();
1105 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1106 {
1107 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1108 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1109 }
1110 RtlReleasePebLock();
1111 }
1112 return STATUS_SUCCESS;
1113 }
1114 FIXME( "ZeroTlsCell not supported on other threads\n" );
1115 return STATUS_NOT_IMPLEMENTED;
1116
1117 case ThreadImpersonationToken:
1118 {
1119 const HANDLE *phToken = data;
1120 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1121 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1122 SERVER_START_REQ( set_thread_info )
1123 {
1124 req->handle = wine_server_obj_handle( handle );
1125 req->token = wine_server_obj_handle( *phToken );
1126 req->mask = SET_THREAD_INFO_TOKEN;
1127 status = wine_server_call( req );
1128 }
1129 SERVER_END_REQ;
1130 }
1131 return status;
1132 case ThreadBasePriority:
1133 {
1134 const DWORD *pprio = data;
1135 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1136 SERVER_START_REQ( set_thread_info )
1137 {
1138 req->handle = wine_server_obj_handle( handle );
1139 req->priority = *pprio;
1140 req->mask = SET_THREAD_INFO_PRIORITY;
1141 status = wine_server_call( req );
1142 }
1143 SERVER_END_REQ;
1144 }
1145 return status;
1146 case ThreadAffinityMask:
1147 {
1148 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1149 ULONG_PTR req_aff;
1150
1151 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1152 req_aff = *(const ULONG_PTR *)data;
1153 if ((ULONG)req_aff == ~0u) req_aff = affinity_mask;
1154 else if (req_aff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1155 else if (!req_aff) return STATUS_INVALID_PARAMETER;
1156 SERVER_START_REQ( set_thread_info )
1157 {
1158 req->handle = wine_server_obj_handle( handle );
1159 req->affinity = req_aff;
1160 req->mask = SET_THREAD_INFO_AFFINITY;
1161 status = wine_server_call( req );
1162 }
1163 SERVER_END_REQ;
1164 }
1165 return status;
1166 case ThreadHideFromDebugger:
1167 /* pretend the call succeeded to satisfy some code protectors */
1168 return STATUS_SUCCESS;
1169
1170 case ThreadBasicInformation:
1171 case ThreadTimes:
1172 case ThreadPriority:
1173 case ThreadDescriptorTableEntry:
1174 case ThreadEnableAlignmentFaultFixup:
1175 case ThreadEventPair_Reusable:
1176 case ThreadQuerySetWin32StartAddress:
1177 case ThreadPerformanceCount:
1178 case ThreadAmILastThread:
1179 case ThreadIdealProcessor:
1180 case ThreadPriorityBoost:
1181 case ThreadSetTlsArrayAddress:
1182 case ThreadIsIoPending:
1183 default:
1184 FIXME( "info class %d not supported yet\n", class );
1185 return STATUS_NOT_IMPLEMENTED;
1186 }
1187 }
1188
1189 /******************************************************************************
1190 * NtGetCurrentProcessorNumber (NTDLL.@)
1191 *
1192 * Return the processor, on which the thread is running
1193 *
1194 */
1195 ULONG WINAPI NtGetCurrentProcessorNumber(void)
1196 {
1197 ULONG processor;
1198
1199 #if defined(__linux__) && defined(__NR_getcpu)
1200 int res = syscall(__NR_getcpu, &processor, NULL, NULL);
1201 if (res != -1) return processor;
1202 #endif
1203
1204 if (NtCurrentTeb()->Peb->NumberOfProcessors > 1)
1205 {
1206 ULONG_PTR thread_mask, processor_mask;
1207 NTSTATUS status;
1208
1209 status = NtQueryInformationThread(GetCurrentThread(), ThreadAffinityMask,
1210 &thread_mask, sizeof(thread_mask), NULL);
1211 if (status == STATUS_SUCCESS)
1212 {
1213 for (processor = 0; processor < NtCurrentTeb()->Peb->NumberOfProcessors; processor++)
1214 {
1215 processor_mask = (1 << processor);
1216 if (thread_mask & processor_mask)
1217 {
1218 if (thread_mask != processor_mask)
1219 FIXME("need multicore support (%d processors)\n",
1220 NtCurrentTeb()->Peb->NumberOfProcessors);
1221 return processor;
1222 }
1223 }
1224 }
1225 }
1226
1227 /* fallback to the first processor */
1228 return 0;
1229 }
1230
This page was automatically generated by the
LXR engine.
Visit the LXR main site for more
information.