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