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