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