ntdll: Handle SIMD exceptions.
[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 <sys/types.h>
26 #ifdef HAVE_SYS_MMAN_H
27 #include <sys/mman.h>
28 #endif
29 #ifdef HAVE_SYS_TIMES_H
30 #include <sys/times.h>
31 #endif
32
33 #define NONAMELESSUNION
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "thread.h"
37 #include "winternl.h"
38 #include "wine/library.h"
39 #include "wine/server.h"
40 #include "wine/pthread.h"
41 #include "wine/debug.h"
42 #include "ntdll_misc.h"
43 #include "wine/exception.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(thread);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
47
48 /* info passed to a starting thread */
49 struct startup_info
50 {
51     struct wine_pthread_thread_info pthread_info;
52     PRTL_THREAD_START_ROUTINE       entry_point;
53     void                           *entry_arg;
54 };
55
56 static PEB_LDR_DATA ldr;
57 static RTL_USER_PROCESS_PARAMETERS params;  /* default parameters if no parent */
58 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
59 static RTL_BITMAP tls_bitmap;
60 static RTL_BITMAP tls_expansion_bitmap;
61 static LIST_ENTRY tls_links;
62 static size_t sigstack_total_size;
63 static ULONG sigstack_zero_bits;
64
65 struct wine_pthread_functions pthread_functions = { NULL };
66
67
68 static RTL_CRITICAL_SECTION ldt_section;
69 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
70 {
71     0, 0, &ldt_section,
72     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
73       0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
74 };
75 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
76 static sigset_t ldt_sigset;
77
78 /***********************************************************************
79  *           locking for LDT routines
80  */
81 static void ldt_lock(void)
82 {
83     sigset_t sigset;
84
85     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
86     RtlEnterCriticalSection( &ldt_section );
87     if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
88 }
89
90 static void ldt_unlock(void)
91 {
92     if (ldt_section.RecursionCount == 1)
93     {
94         sigset_t sigset = ldt_sigset;
95         RtlLeaveCriticalSection( &ldt_section );
96         pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
97     }
98     else RtlLeaveCriticalSection( &ldt_section );
99 }
100
101
102 /***********************************************************************
103  *           init_teb
104  */
105 static inline NTSTATUS init_teb( TEB *teb )
106 {
107     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
108     struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
109
110     teb->Tib.ExceptionList = (void *)~0UL;
111     teb->Tib.StackBase     = (void *)~0UL;
112     teb->Tib.Self          = &teb->Tib;
113     teb->StaticUnicodeString.Buffer        = teb->StaticUnicodeBuffer;
114     teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
115
116     if (!(thread_regs->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
117     thread_data->request_fd = -1;
118     thread_data->reply_fd   = -1;
119     thread_data->wait_fd[0] = -1;
120     thread_data->wait_fd[1] = -1;
121
122     return STATUS_SUCCESS;
123 }
124
125
126 /***********************************************************************
127  *           fix_unicode_string
128  *
129  * Make sure the unicode string doesn't point beyond the end pointer
130  */
131 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
132 {
133     if ((char *)str->Buffer >= end_ptr)
134     {
135         str->Length = str->MaximumLength = 0;
136         str->Buffer = NULL;
137         return;
138     }
139     if ((char *)str->Buffer + str->MaximumLength > end_ptr)
140     {
141         str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
142     }
143     if (str->Length >= str->MaximumLength)
144     {
145         if (str->MaximumLength >= sizeof(WCHAR))
146             str->Length = str->MaximumLength - sizeof(WCHAR);
147         else
148             str->Length = str->MaximumLength = 0;
149     }
150 }
151
152
153 /***********************************************************************
154  *           init_user_process_params
155  *
156  * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
157  */
158 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
159 {
160     void *ptr;
161     SIZE_T env_size;
162     NTSTATUS status;
163     RTL_USER_PROCESS_PARAMETERS *params = NULL;
164
165     status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &info_size,
166                                       MEM_COMMIT, PAGE_READWRITE );
167     if (status != STATUS_SUCCESS) return status;
168
169     params->AllocationSize = info_size;
170     NtCurrentTeb()->Peb->ProcessParameters = params;
171
172     SERVER_START_REQ( get_startup_info )
173     {
174         wine_server_set_reply( req, params, info_size );
175         if (!(status = wine_server_call( req )))
176         {
177             info_size = wine_server_reply_size( reply );
178             *exe_file = reply->exe_file;
179             params->hStdInput  = reply->hstdin;
180             params->hStdOutput = reply->hstdout;
181             params->hStdError  = reply->hstderr;
182         }
183     }
184     SERVER_END_REQ;
185     if (status != STATUS_SUCCESS) return status;
186
187     if (params->Size > info_size) params->Size = info_size;
188
189     /* make sure the strings are valid */
190     fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
191     fix_unicode_string( &params->DllPath, (char *)info_size );
192     fix_unicode_string( &params->ImagePathName, (char *)info_size );
193     fix_unicode_string( &params->CommandLine, (char *)info_size );
194     fix_unicode_string( &params->WindowTitle, (char *)info_size );
195     fix_unicode_string( &params->Desktop, (char *)info_size );
196     fix_unicode_string( &params->ShellInfo, (char *)info_size );
197     fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
198
199     /* environment needs to be a separate memory block */
200     env_size = info_size - params->Size;
201     if (!env_size) env_size = 1;
202     ptr = NULL;
203     status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
204                                       MEM_COMMIT, PAGE_READWRITE );
205     if (status != STATUS_SUCCESS) return status;
206     memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
207     params->Environment = ptr;
208
209     RtlNormalizeProcessParams( params );
210     return status;
211 }
212
213
214 /***********************************************************************
215  *           thread_init
216  *
217  * Setup the initial thread.
218  *
219  * NOTES: The first allocated TEB on NT is at 0x7ffde000.
220  */
221 HANDLE thread_init(void)
222 {
223     PEB *peb;
224     TEB *teb;
225     void *addr;
226     SIZE_T size, info_size;
227     HANDLE exe_file = 0;
228     struct ntdll_thread_data *thread_data;
229     struct ntdll_thread_regs *thread_regs;
230     struct wine_pthread_thread_info thread_info;
231     static struct debug_info debug_info;  /* debug info for initial thread */
232
233     virtual_init();
234
235     /* reserve space for shared user data */
236
237     addr = (void *)0x7ffe0000;
238     size = 0x10000;
239     NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE, PAGE_READONLY );
240
241     /* allocate and initialize the PEB */
242
243     addr = NULL;
244     size = sizeof(*peb);
245     NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
246                              MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
247     peb = addr;
248
249     peb->NumberOfProcessors = 1;
250     peb->ProcessParameters  = &params;
251     peb->TlsBitmap          = &tls_bitmap;
252     peb->TlsExpansionBitmap = &tls_expansion_bitmap;
253     peb->LdrData            = &ldr;
254     params.CurrentDirectory.DosPath.Buffer = current_dir;
255     params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
256     params.wShowWindow = 1; /* SW_SHOWNORMAL */
257     RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
258     RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
259                          sizeof(peb->TlsExpansionBitmapBits) * 8 );
260     InitializeListHead( &ldr.InLoadOrderModuleList );
261     InitializeListHead( &ldr.InMemoryOrderModuleList );
262     InitializeListHead( &ldr.InInitializationOrderModuleList );
263     InitializeListHead( &tls_links );
264
265     /* allocate and initialize the initial TEB */
266
267     sigstack_total_size = get_signal_stack_total_size();
268     while (1 << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
269     assert( 1 << sigstack_zero_bits == sigstack_total_size );  /* must be a power of 2 */
270     assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
271     thread_info.teb_size = sigstack_total_size;
272
273     addr = NULL;
274     size = sigstack_total_size;
275     NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
276                              &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
277     teb = addr;
278     teb->Peb = peb;
279     thread_info.teb_size = size;
280     init_teb( teb );
281     thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
282     thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
283     thread_data->debug_info = &debug_info;
284     InsertHeadList( &tls_links, &teb->TlsLinks );
285
286     thread_info.stack_base = NULL;
287     thread_info.stack_size = 0;
288     thread_info.teb_base   = teb;
289     thread_info.teb_sel    = thread_regs->fs;
290     wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
291     pthread_functions.init_current_teb( &thread_info );
292     pthread_functions.init_thread( &thread_info );
293     virtual_init_threading();
294
295     debug_info.str_pos = debug_info.strings;
296     debug_info.out_pos = debug_info.output;
297     debug_init();
298
299     /* setup the server connection */
300     server_init_process();
301     info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
302
303     /* create the process heap */
304     if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
305     {
306         MESSAGE( "wine: failed to create the process heap\n" );
307         exit(1);
308     }
309
310     /* allocate user parameters */
311     if (info_size)
312     {
313         init_user_process_params( info_size, &exe_file );
314     }
315     else
316     {
317         /* This is wine specific: we have no parent (we're started from unix)
318          * so, create a simple console with bare handles to unix stdio
319          */
320         wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  OBJ_INHERIT, &params.hStdInput );
321         wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
322         wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
323     }
324
325     /* initialize LDT locking */
326     wine_ldt_init_locking( ldt_lock, ldt_unlock );
327
328     return exe_file;
329 }
330
331 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
332 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
333 {
334     static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
335     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
336     UNICODE_STRING module_name;
337     ANSI_STRING func_name;
338     HMODULE kernel32_handle;
339
340     if (unhandled_exception_filter) return unhandled_exception_filter;
341
342     RtlInitUnicodeString(&module_name, kernel32W);
343     RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
344
345     if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
346         LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
347                                 (void **)&unhandled_exception_filter );
348
349     return unhandled_exception_filter;
350 }
351
352 /***********************************************************************
353  *           call_thread_func
354  *
355  * Hack to make things compatible with the thread procedures used by kernel32.CreateThread.
356  */
357 static void DECLSPEC_NORETURN call_thread_func( PRTL_THREAD_START_ROUTINE rtl_func, void *arg )
358 {
359     LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)rtl_func;
360     DWORD exit_code;
361     BOOL last;
362
363     MODULE_DllThreadAttach( NULL );
364
365     if (TRACE_ON(relay))
366         DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
367
368     exit_code = func( arg );
369
370     /* send the exit code to the server */
371     SERVER_START_REQ( terminate_thread )
372     {
373         req->handle    = GetCurrentThread();
374         req->exit_code = exit_code;
375         wine_server_call( req );
376         last = reply->last;
377     }
378     SERVER_END_REQ;
379
380     if (last)
381     {
382         LdrShutdownProcess();
383         exit( exit_code );
384     }
385     else
386     {
387         LdrShutdownThread();
388         server_exit_thread( exit_code );
389     }
390 }
391
392
393 /***********************************************************************
394  *           start_thread
395  *
396  * Startup routine for a newly created thread.
397  */
398 static void start_thread( struct wine_pthread_thread_info *info )
399 {
400     TEB *teb = info->teb_base;
401     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
402     struct startup_info *startup_info = (struct startup_info *)info;
403     PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
404     void *arg = startup_info->entry_arg;
405     struct debug_info debug_info;
406     SIZE_T size, page_size = getpagesize();
407
408     debug_info.str_pos = debug_info.strings;
409     debug_info.out_pos = debug_info.output;
410     thread_data->debug_info = &debug_info;
411
412     pthread_functions.init_current_teb( info );
413     SIGNAL_Init();
414     server_init_thread( info->pid, info->tid, func );
415     pthread_functions.init_thread( info );
416
417     /* allocate a memory view for the stack */
418     size = info->stack_size;
419     teb->DeallocationStack = info->stack_base;
420     NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
421                              &size, MEM_SYSTEM, PAGE_READWRITE );
422     /* limit is lower than base since the stack grows down */
423     teb->Tib.StackBase  = (char *)info->stack_base + info->stack_size;
424     teb->Tib.StackLimit = (char *)info->stack_base + page_size;
425
426     /* setup the guard page */
427     size = page_size;
428     NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
429
430     pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
431
432     RtlAcquirePebLock();
433     InsertHeadList( &tls_links, &teb->TlsLinks );
434     RtlReleasePebLock();
435
436     /* NOTE: Windows does not have an exception handler around the call to
437      * the thread attach. We do for ease of debugging */
438     if (get_unhandled_exception_filter())
439     {
440         __TRY
441         {
442             call_thread_func( func, arg );
443         }
444         __EXCEPT(get_unhandled_exception_filter())
445         {
446             NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
447         }
448         __ENDTRY
449     }
450     else
451         call_thread_func( func, arg );
452 }
453
454
455 /***********************************************************************
456  *              RtlCreateUserThread   (NTDLL.@)
457  */
458 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
459                                      BOOLEAN suspended, PVOID stack_addr,
460                                      SIZE_T stack_reserve, SIZE_T stack_commit,
461                                      PRTL_THREAD_START_ROUTINE start, void *param,
462                                      HANDLE *handle_ptr, CLIENT_ID *id )
463 {
464     sigset_t sigset;
465     struct ntdll_thread_data *thread_data;
466     struct ntdll_thread_regs *thread_regs = NULL;
467     struct startup_info *info = NULL;
468     void *addr = NULL;
469     HANDLE handle = 0;
470     TEB *teb;
471     DWORD tid = 0;
472     int request_pipe[2];
473     NTSTATUS status;
474     SIZE_T size, page_size = getpagesize();
475
476     if (process != NtCurrentProcess())
477     {
478         apc_call_t call;
479         apc_result_t result;
480
481         call.create_thread.type    = APC_CREATE_THREAD;
482         call.create_thread.func    = start;
483         call.create_thread.arg     = param;
484         call.create_thread.reserve = stack_reserve;
485         call.create_thread.commit  = stack_commit;
486         call.create_thread.suspend = suspended;
487         status = NTDLL_queue_process_apc( process, &call, &result );
488         if (status != STATUS_SUCCESS) return status;
489
490         if (result.create_thread.status == STATUS_SUCCESS)
491         {
492             if (id) id->UniqueThread = (HANDLE)result.create_thread.tid;
493             if (handle_ptr) *handle_ptr = result.create_thread.handle;
494             else NtClose( result.create_thread.handle );
495         }
496         return result.create_thread.status;
497     }
498
499     if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
500     fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
501     wine_server_send_fd( request_pipe[0] );
502
503     SERVER_START_REQ( new_thread )
504     {
505         req->access     = THREAD_ALL_ACCESS;
506         req->attributes = 0;  /* FIXME */
507         req->suspend    = suspended;
508         req->request_fd = request_pipe[0];
509         if (!(status = wine_server_call( req )))
510         {
511             handle = reply->handle;
512             tid = reply->tid;
513         }
514         close( request_pipe[0] );
515     }
516     SERVER_END_REQ;
517
518     if (status)
519     {
520         close( request_pipe[1] );
521         return status;
522     }
523
524     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
525
526     addr = NULL;
527     size = sigstack_total_size;
528     if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
529                                            &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
530         goto error;
531     teb = addr;
532     teb->Peb = NtCurrentTeb()->Peb;
533     info = (struct startup_info *)(teb + 1);
534     info->pthread_info.teb_size = size;
535     if ((status = init_teb( teb ))) goto error;
536
537     teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
538     teb->ClientId.UniqueThread  = (HANDLE)tid;
539
540     thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
541     thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
542     thread_data->request_fd  = request_pipe[1];
543
544     info->pthread_info.teb_base = teb;
545     info->pthread_info.teb_sel  = thread_regs->fs;
546
547     /* inherit debug registers from parent thread */
548     thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
549     thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
550     thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
551     thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
552     thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
553     thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
554
555     if (!stack_reserve || !stack_commit)
556     {
557         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
558         if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
559         if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
560     }
561     if (stack_reserve < stack_commit) stack_reserve = stack_commit;
562     stack_reserve += page_size;  /* for the guard page */
563     stack_reserve = (stack_reserve + 0xffff) & ~0xffff;  /* round to 64K boundary */
564     if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024;  /* Xlib needs a large stack */
565
566     info->pthread_info.stack_base = NULL;
567     info->pthread_info.stack_size = stack_reserve;
568     info->pthread_info.entry      = start_thread;
569     info->entry_point             = start;
570     info->entry_arg               = param;
571
572     if (pthread_functions.create_thread( &info->pthread_info ) == -1)
573     {
574         status = STATUS_NO_MEMORY;
575         goto error;
576     }
577     pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
578
579     if (id) id->UniqueThread = (HANDLE)tid;
580     if (handle_ptr) *handle_ptr = handle;
581     else NtClose( handle );
582
583     return STATUS_SUCCESS;
584
585 error:
586     if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
587     if (addr)
588     {
589         SIZE_T size = 0;
590         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
591     }
592     if (handle) NtClose( handle );
593     pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
594     close( request_pipe[1] );
595     return status;
596 }
597
598
599 /***********************************************************************
600  *           RtlExitUserThread  (NTDLL.@)
601  */
602 void WINAPI RtlExitUserThread( ULONG status )
603 {
604     LdrShutdownThread();
605     server_exit_thread( status );
606 }
607
608
609 /***********************************************************************
610  *              NtOpenThread   (NTDLL.@)
611  *              ZwOpenThread   (NTDLL.@)
612  */
613 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
614                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
615 {
616     NTSTATUS ret;
617
618     SERVER_START_REQ( open_thread )
619     {
620         req->tid        = (thread_id_t)id->UniqueThread;
621         req->access     = access;
622         req->attributes = attr ? attr->Attributes : 0;
623         ret = wine_server_call( req );
624         *handle = reply->handle;
625     }
626     SERVER_END_REQ;
627     return ret;
628 }
629
630
631 /******************************************************************************
632  *              NtSuspendThread   (NTDLL.@)
633  *              ZwSuspendThread   (NTDLL.@)
634  */
635 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
636 {
637     NTSTATUS ret;
638
639     SERVER_START_REQ( suspend_thread )
640     {
641         req->handle = handle;
642         if (!(ret = wine_server_call( req ))) *count = reply->count;
643     }
644     SERVER_END_REQ;
645     return ret;
646 }
647
648
649 /******************************************************************************
650  *              NtResumeThread   (NTDLL.@)
651  *              ZwResumeThread   (NTDLL.@)
652  */
653 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
654 {
655     NTSTATUS ret;
656
657     SERVER_START_REQ( resume_thread )
658     {
659         req->handle = handle;
660         if (!(ret = wine_server_call( req ))) *count = reply->count;
661     }
662     SERVER_END_REQ;
663     return ret;
664 }
665
666
667 /******************************************************************************
668  *              NtAlertResumeThread   (NTDLL.@)
669  *              ZwAlertResumeThread   (NTDLL.@)
670  */
671 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
672 {
673     FIXME( "stub: should alert thread %p\n", handle );
674     return NtResumeThread( handle, count );
675 }
676
677
678 /******************************************************************************
679  *              NtAlertThread   (NTDLL.@)
680  *              ZwAlertThread   (NTDLL.@)
681  */
682 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
683 {
684     FIXME( "stub: %p\n", handle );
685     return STATUS_NOT_IMPLEMENTED;
686 }
687
688
689 /******************************************************************************
690  *              NtTerminateThread  (NTDLL.@)
691  *              ZwTerminateThread  (NTDLL.@)
692  */
693 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
694 {
695     NTSTATUS ret;
696     BOOL self, last;
697
698     SERVER_START_REQ( terminate_thread )
699     {
700         req->handle    = handle;
701         req->exit_code = exit_code;
702         ret = wine_server_call( req );
703         self = !ret && reply->self;
704         last = reply->last;
705     }
706     SERVER_END_REQ;
707
708     if (self)
709     {
710         if (last) exit( exit_code );
711         else server_abort_thread( exit_code );
712     }
713     return ret;
714 }
715
716
717 /******************************************************************************
718  *              NtQueueApcThread  (NTDLL.@)
719  */
720 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
721                                   ULONG_PTR arg2, ULONG_PTR arg3 )
722 {
723     NTSTATUS ret;
724     SERVER_START_REQ( queue_apc )
725     {
726         req->thread = handle;
727         if (func)
728         {
729             req->call.type         = APC_USER;
730             req->call.user.func    = func;
731             req->call.user.args[0] = arg1;
732             req->call.user.args[1] = arg2;
733             req->call.user.args[2] = arg3;
734         }
735         else req->call.type = APC_NONE;  /* wake up only */
736         ret = wine_server_call( req );
737     }
738     SERVER_END_REQ;
739     return ret;
740 }
741
742
743 /***********************************************************************
744  *              NtSetContextThread  (NTDLL.@)
745  *              ZwSetContextThread  (NTDLL.@)
746  */
747 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
748 {
749     NTSTATUS ret;
750     DWORD dummy, i;
751     BOOL self = FALSE;
752
753 #ifdef __i386__
754     /* on i386 debug registers always require a server call */
755     self = (handle == GetCurrentThread());
756     if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
757     {
758         struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
759         self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
760                 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
761                 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
762     }
763 #endif
764
765     if (!self)
766     {
767         SERVER_START_REQ( set_thread_context )
768         {
769             req->handle  = handle;
770             req->flags   = context->ContextFlags;
771             req->suspend = 0;
772             wine_server_add_data( req, context, sizeof(*context) );
773             ret = wine_server_call( req );
774             self = reply->self;
775         }
776         SERVER_END_REQ;
777
778         if (ret == STATUS_PENDING)
779         {
780             if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
781             {
782                 for (i = 0; i < 100; i++)
783                 {
784                     SERVER_START_REQ( set_thread_context )
785                     {
786                         req->handle  = handle;
787                         req->flags   = context->ContextFlags;
788                         req->suspend = 0;
789                         wine_server_add_data( req, context, sizeof(*context) );
790                         ret = wine_server_call( req );
791                     }
792                     SERVER_END_REQ;
793                     if (ret != STATUS_PENDING) break;
794                     NtYieldExecution();
795                 }
796                 NtResumeThread( handle, &dummy );
797             }
798             if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
799         }
800
801         if (ret) return ret;
802     }
803
804     if (self) set_cpu_context( context );
805     return STATUS_SUCCESS;
806 }
807
808
809 /* copy a context structure according to the flags */
810 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
811 {
812 #ifdef __i386__
813     flags &= ~CONTEXT_i386;  /* get rid of CPU id */
814     if (flags & CONTEXT_INTEGER)
815     {
816         to->Eax = from->Eax;
817         to->Ebx = from->Ebx;
818         to->Ecx = from->Ecx;
819         to->Edx = from->Edx;
820         to->Esi = from->Esi;
821         to->Edi = from->Edi;
822     }
823     if (flags & CONTEXT_CONTROL)
824     {
825         to->Ebp    = from->Ebp;
826         to->Esp    = from->Esp;
827         to->Eip    = from->Eip;
828         to->SegCs  = from->SegCs;
829         to->SegSs  = from->SegSs;
830         to->EFlags = from->EFlags;
831     }
832     if (flags & CONTEXT_SEGMENTS)
833     {
834         to->SegDs = from->SegDs;
835         to->SegEs = from->SegEs;
836         to->SegFs = from->SegFs;
837         to->SegGs = from->SegGs;
838     }
839     if (flags & CONTEXT_DEBUG_REGISTERS)
840     {
841         to->Dr0 = from->Dr0;
842         to->Dr1 = from->Dr1;
843         to->Dr2 = from->Dr2;
844         to->Dr3 = from->Dr3;
845         to->Dr6 = from->Dr6;
846         to->Dr7 = from->Dr7;
847     }
848     if (flags & CONTEXT_FLOATING_POINT)
849     {
850         to->FloatSave = from->FloatSave;
851     }
852 #elif defined(__x86_64__)
853     flags &= ~CONTEXT_AMD64;  /* get rid of CPU id */
854     if (flags & CONTEXT_CONTROL)
855     {
856         to->Rbp    = from->Rbp;
857         to->Rip    = from->Rip;
858         to->Rsp    = from->Rsp;
859         to->SegCs  = from->SegCs;
860         to->SegSs  = from->SegSs;
861         to->EFlags = from->EFlags;
862         to->MxCsr  = from->MxCsr;
863     }
864     if (flags & CONTEXT_INTEGER)
865     {
866         to->Rax = from->Rax;
867         to->Rcx = from->Rcx;
868         to->Rdx = from->Rdx;
869         to->Rbx = from->Rbx;
870         to->Rsi = from->Rsi;
871         to->Rdi = from->Rdi;
872         to->R8  = from->R8;
873         to->R9  = from->R9;
874         to->R10 = from->R10;
875         to->R11 = from->R11;
876         to->R12 = from->R12;
877         to->R13 = from->R13;
878         to->R14 = from->R14;
879         to->R15 = from->R15;
880     }
881     if (flags & CONTEXT_SEGMENTS)
882     {
883         to->SegDs = from->SegDs;
884         to->SegEs = from->SegEs;
885         to->SegFs = from->SegFs;
886         to->SegGs = from->SegGs;
887     }
888     if (flags & CONTEXT_FLOATING_POINT)
889     {
890         to->u.FltSave = from->u.FltSave;
891     }
892     if (flags & CONTEXT_DEBUG_REGISTERS)
893     {
894         to->Dr0 = from->Dr0;
895         to->Dr1 = from->Dr1;
896         to->Dr2 = from->Dr2;
897         to->Dr3 = from->Dr3;
898         to->Dr6 = from->Dr6;
899         to->Dr7 = from->Dr7;
900     }
901 #elif defined(__sparc__)
902     flags &= ~CONTEXT_SPARC;  /* get rid of CPU id */
903     if (flags & CONTEXT_CONTROL)
904     {
905         to->psr = from->psr;
906         to->pc  = from->pc;
907         to->npc = from->npc;
908         to->y   = from->y;
909         to->wim = from->wim;
910         to->tbr = from->tbr;
911     }
912     if (flags & CONTEXT_INTEGER)
913     {
914         to->g0 = from->g0;
915         to->g1 = from->g1;
916         to->g2 = from->g2;
917         to->g3 = from->g3;
918         to->g4 = from->g4;
919         to->g5 = from->g5;
920         to->g6 = from->g6;
921         to->g7 = from->g7;
922         to->o0 = from->o0;
923         to->o1 = from->o1;
924         to->o2 = from->o2;
925         to->o3 = from->o3;
926         to->o4 = from->o4;
927         to->o5 = from->o5;
928         to->o6 = from->o6;
929         to->o7 = from->o7;
930         to->l0 = from->l0;
931         to->l1 = from->l1;
932         to->l2 = from->l2;
933         to->l3 = from->l3;
934         to->l4 = from->l4;
935         to->l5 = from->l5;
936         to->l6 = from->l6;
937         to->l7 = from->l7;
938         to->i0 = from->i0;
939         to->i1 = from->i1;
940         to->i2 = from->i2;
941         to->i3 = from->i3;
942         to->i4 = from->i4;
943         to->i5 = from->i5;
944         to->i6 = from->i6;
945         to->i7 = from->i7;
946     }
947     if (flags & CONTEXT_FLOATING_POINT)
948     {
949         /* FIXME */
950     }
951 #elif defined(__powerpc__)
952     /* Has no CPU id */
953     if (flags & CONTEXT_CONTROL)
954     {
955         to->Msr = from->Msr;
956         to->Ctr = from->Ctr;
957         to->Iar = from->Iar;
958     }
959     if (flags & CONTEXT_INTEGER)
960     {
961         to->Gpr0  = from->Gpr0;
962         to->Gpr1  = from->Gpr1;
963         to->Gpr2  = from->Gpr2;
964         to->Gpr3  = from->Gpr3;
965         to->Gpr4  = from->Gpr4;
966         to->Gpr5  = from->Gpr5;
967         to->Gpr6  = from->Gpr6;
968         to->Gpr7  = from->Gpr7;
969         to->Gpr8  = from->Gpr8;
970         to->Gpr9  = from->Gpr9;
971         to->Gpr10 = from->Gpr10;
972         to->Gpr11 = from->Gpr11;
973         to->Gpr12 = from->Gpr12;
974         to->Gpr13 = from->Gpr13;
975         to->Gpr14 = from->Gpr14;
976         to->Gpr15 = from->Gpr15;
977         to->Gpr16 = from->Gpr16;
978         to->Gpr17 = from->Gpr17;
979         to->Gpr18 = from->Gpr18;
980         to->Gpr19 = from->Gpr19;
981         to->Gpr20 = from->Gpr20;
982         to->Gpr21 = from->Gpr21;
983         to->Gpr22 = from->Gpr22;
984         to->Gpr23 = from->Gpr23;
985         to->Gpr24 = from->Gpr24;
986         to->Gpr25 = from->Gpr25;
987         to->Gpr26 = from->Gpr26;
988         to->Gpr27 = from->Gpr27;
989         to->Gpr28 = from->Gpr28;
990         to->Gpr29 = from->Gpr29;
991         to->Gpr30 = from->Gpr30;
992         to->Gpr31 = from->Gpr31;
993         to->Xer   = from->Xer;
994         to->Cr    = from->Cr;
995     }
996     if (flags & CONTEXT_FLOATING_POINT)
997     {
998         to->Fpr0  = from->Fpr0;
999         to->Fpr1  = from->Fpr1;
1000         to->Fpr2  = from->Fpr2;
1001         to->Fpr3  = from->Fpr3;
1002         to->Fpr4  = from->Fpr4;
1003         to->Fpr5  = from->Fpr5;
1004         to->Fpr6  = from->Fpr6;
1005         to->Fpr7  = from->Fpr7;
1006         to->Fpr8  = from->Fpr8;
1007         to->Fpr9  = from->Fpr9;
1008         to->Fpr10 = from->Fpr10;
1009         to->Fpr11 = from->Fpr11;
1010         to->Fpr12 = from->Fpr12;
1011         to->Fpr13 = from->Fpr13;
1012         to->Fpr14 = from->Fpr14;
1013         to->Fpr15 = from->Fpr15;
1014         to->Fpr16 = from->Fpr16;
1015         to->Fpr17 = from->Fpr17;
1016         to->Fpr18 = from->Fpr18;
1017         to->Fpr19 = from->Fpr19;
1018         to->Fpr20 = from->Fpr20;
1019         to->Fpr21 = from->Fpr21;
1020         to->Fpr22 = from->Fpr22;
1021         to->Fpr23 = from->Fpr23;
1022         to->Fpr24 = from->Fpr24;
1023         to->Fpr25 = from->Fpr25;
1024         to->Fpr26 = from->Fpr26;
1025         to->Fpr27 = from->Fpr27;
1026         to->Fpr28 = from->Fpr28;
1027         to->Fpr29 = from->Fpr29;
1028         to->Fpr30 = from->Fpr30;
1029         to->Fpr31 = from->Fpr31;
1030         to->Fpscr = from->Fpscr;
1031     }
1032 #else
1033 #error You must implement context copying for your CPU
1034 #endif
1035 }
1036
1037
1038 /***********************************************************************
1039  *              NtGetContextThread  (NTDLL.@)
1040  *              ZwGetContextThread  (NTDLL.@)
1041  */
1042 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1043 {
1044     NTSTATUS ret;
1045     CONTEXT ctx;
1046     DWORD dummy, i;
1047     DWORD needed_flags = context->ContextFlags;
1048     BOOL self = (handle == GetCurrentThread());
1049
1050 #ifdef __i386__
1051     /* on i386 debug registers always require a server call */
1052     if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1053 #endif
1054
1055     if (!self)
1056     {
1057         SERVER_START_REQ( get_thread_context )
1058         {
1059             req->handle  = handle;
1060             req->flags   = context->ContextFlags;
1061             req->suspend = 0;
1062             wine_server_set_reply( req, &ctx, sizeof(ctx) );
1063             ret = wine_server_call( req );
1064             self = reply->self;
1065         }
1066         SERVER_END_REQ;
1067
1068         if (ret == STATUS_PENDING)
1069         {
1070             if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1071             {
1072                 for (i = 0; i < 100; i++)
1073                 {
1074                     SERVER_START_REQ( get_thread_context )
1075                     {
1076                         req->handle  = handle;
1077                         req->flags   = context->ContextFlags;
1078                         req->suspend = 0;
1079                         wine_server_set_reply( req, &ctx, sizeof(ctx) );
1080                         ret = wine_server_call( req );
1081                     }
1082                     SERVER_END_REQ;
1083                     if (ret != STATUS_PENDING) break;
1084                     NtYieldExecution();
1085                 }
1086                 NtResumeThread( handle, &dummy );
1087             }
1088             if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1089         }
1090         if (ret) return ret;
1091         copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1092         needed_flags &= ~ctx.ContextFlags;
1093     }
1094
1095     if (self)
1096     {
1097         if (needed_flags)
1098         {
1099             get_cpu_context( &ctx );
1100             copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1101         }
1102 #ifdef __i386__
1103         /* update the cached version of the debug registers */
1104         if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1105         {
1106             struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1107             regs->dr0 = context->Dr0;
1108             regs->dr1 = context->Dr1;
1109             regs->dr2 = context->Dr2;
1110             regs->dr3 = context->Dr3;
1111             regs->dr6 = context->Dr6;
1112             regs->dr7 = context->Dr7;
1113         }
1114 #endif
1115     }
1116     return STATUS_SUCCESS;
1117 }
1118
1119
1120 /******************************************************************************
1121  *              NtQueryInformationThread  (NTDLL.@)
1122  *              ZwQueryInformationThread  (NTDLL.@)
1123  */
1124 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1125                                           void *data, ULONG length, ULONG *ret_len )
1126 {
1127     NTSTATUS status;
1128
1129     switch(class)
1130     {
1131     case ThreadBasicInformation:
1132         {
1133             THREAD_BASIC_INFORMATION info;
1134
1135             SERVER_START_REQ( get_thread_info )
1136             {
1137                 req->handle = handle;
1138                 req->tid_in = 0;
1139                 if (!(status = wine_server_call( req )))
1140                 {
1141                     info.ExitStatus             = reply->exit_code;
1142                     info.TebBaseAddress         = reply->teb;
1143                     info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1144                     info.ClientId.UniqueThread  = (HANDLE)reply->tid;
1145                     info.AffinityMask           = reply->affinity;
1146                     info.Priority               = reply->priority;
1147                     info.BasePriority           = reply->priority;  /* FIXME */
1148                 }
1149             }
1150             SERVER_END_REQ;
1151             if (status == STATUS_SUCCESS)
1152             {
1153                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1154                 if (ret_len) *ret_len = min( length, sizeof(info) );
1155             }
1156         }
1157         return status;
1158     case ThreadTimes:
1159         {
1160             KERNEL_USER_TIMES   kusrt;
1161             /* We need to do a server call to get the creation time or exit time */
1162             /* This works on any thread */
1163             SERVER_START_REQ( get_thread_info )
1164             {
1165                 req->handle = handle;
1166                 req->tid_in = 0;
1167                 status = wine_server_call( req );
1168                 if (status == STATUS_SUCCESS)
1169                 {
1170                     NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1171                     NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1172                 }
1173             }
1174             SERVER_END_REQ;
1175             if (status == STATUS_SUCCESS)
1176             {
1177                 /* We call times(2) for kernel time or user time */
1178                 /* We can only (portably) do this for the current thread */
1179                 if (handle == GetCurrentThread())
1180                 {
1181                     struct tms time_buf;
1182                     long clocks_per_sec = sysconf(_SC_CLK_TCK);
1183
1184                     times(&time_buf);
1185                     kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1186                     kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1187                 }
1188                 else
1189                 {
1190                     kusrt.KernelTime.QuadPart = 0;
1191                     kusrt.UserTime.QuadPart = 0;
1192                     FIXME("Cannot get kerneltime or usertime of other threads\n");
1193                 }
1194                 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1195                 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1196             }
1197         }
1198         return status;
1199     case ThreadDescriptorTableEntry:
1200         {
1201 #ifdef __i386__
1202             THREAD_DESCRIPTOR_INFORMATION*      tdi = data;
1203             if (length < sizeof(*tdi))
1204                 status = STATUS_INFO_LENGTH_MISMATCH;
1205             else if (!(tdi->Selector & 4))  /* GDT selector */
1206             {
1207                 unsigned sel = tdi->Selector & ~3;  /* ignore RPL */
1208                 status = STATUS_SUCCESS;
1209                 if (!sel)  /* null selector */
1210                     memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1211                 else
1212                 {
1213                     tdi->Entry.BaseLow                   = 0;
1214                     tdi->Entry.HighWord.Bits.BaseMid     = 0;
1215                     tdi->Entry.HighWord.Bits.BaseHi      = 0;
1216                     tdi->Entry.LimitLow                  = 0xffff;
1217                     tdi->Entry.HighWord.Bits.LimitHi     = 0xf;
1218                     tdi->Entry.HighWord.Bits.Dpl         = 3;
1219                     tdi->Entry.HighWord.Bits.Sys         = 0;
1220                     tdi->Entry.HighWord.Bits.Pres        = 1;
1221                     tdi->Entry.HighWord.Bits.Granularity = 1;
1222                     tdi->Entry.HighWord.Bits.Default_Big = 1;
1223                     tdi->Entry.HighWord.Bits.Type        = 0x12;
1224                     /* it has to be one of the system GDT selectors */
1225                     if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1226                     {
1227                         if (sel == (wine_get_cs() & ~3))
1228                             tdi->Entry.HighWord.Bits.Type |= 8;  /* code segment */
1229                         else status = STATUS_ACCESS_DENIED;
1230                     }
1231                 }
1232             }
1233             else
1234             {
1235                 SERVER_START_REQ( get_selector_entry )
1236                 {
1237                     req->handle = handle;
1238                     req->entry = tdi->Selector >> 3;
1239                     status = wine_server_call( req );
1240                     if (!status)
1241                     {
1242                         if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1243                             status = STATUS_ACCESS_VIOLATION;
1244                         else
1245                         {
1246                             wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1247                             wine_ldt_set_limit( &tdi->Entry, reply->limit );
1248                             wine_ldt_set_flags( &tdi->Entry, reply->flags );
1249                         }
1250                     }
1251                 }
1252                 SERVER_END_REQ;
1253             }
1254             if (status == STATUS_SUCCESS && ret_len)
1255                 /* yes, that's a bit strange, but it's the way it is */
1256                 *ret_len = sizeof(LDT_ENTRY);
1257 #else
1258             status = STATUS_NOT_IMPLEMENTED;
1259 #endif
1260             return status;
1261         }
1262     case ThreadAmILastThread:
1263         {
1264             SERVER_START_REQ(get_thread_info)
1265             {
1266                 req->handle = handle;
1267                 req->tid_in = 0;
1268                 status = wine_server_call( req );
1269                 if (status == STATUS_SUCCESS)
1270                 {
1271                     BOOLEAN last = reply->last;
1272                     if (data) memcpy( data, &last, min( length, sizeof(last) ));
1273                     if (ret_len) *ret_len = min( length, sizeof(last) );
1274                 }
1275             }
1276             SERVER_END_REQ;
1277             return status;
1278         }
1279     case ThreadPriority:
1280     case ThreadBasePriority:
1281     case ThreadAffinityMask:
1282     case ThreadImpersonationToken:
1283     case ThreadEnableAlignmentFaultFixup:
1284     case ThreadEventPair_Reusable:
1285     case ThreadQuerySetWin32StartAddress:
1286     case ThreadZeroTlsCell:
1287     case ThreadPerformanceCount:
1288     case ThreadIdealProcessor:
1289     case ThreadPriorityBoost:
1290     case ThreadSetTlsArrayAddress:
1291     case ThreadIsIoPending:
1292     default:
1293         FIXME( "info class %d not supported yet\n", class );
1294         return STATUS_NOT_IMPLEMENTED;
1295     }
1296 }
1297
1298
1299 /******************************************************************************
1300  *              NtSetInformationThread  (NTDLL.@)
1301  *              ZwSetInformationThread  (NTDLL.@)
1302  */
1303 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1304                                         LPCVOID data, ULONG length )
1305 {
1306     NTSTATUS status;
1307     switch(class)
1308     {
1309     case ThreadZeroTlsCell:
1310         if (handle == GetCurrentThread())
1311         {
1312             LIST_ENTRY *entry;
1313             DWORD index;
1314
1315             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1316             index = *(const DWORD *)data;
1317             if (index < TLS_MINIMUM_AVAILABLE)
1318             {
1319                 RtlAcquirePebLock();
1320                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1321                 {
1322                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1323                     teb->TlsSlots[index] = 0;
1324                 }
1325                 RtlReleasePebLock();
1326             }
1327             else
1328             {
1329                 index -= TLS_MINIMUM_AVAILABLE;
1330                 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1331                     return STATUS_INVALID_PARAMETER;
1332                 RtlAcquirePebLock();
1333                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1334                 {
1335                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1336                     if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1337                 }
1338                 RtlReleasePebLock();
1339             }
1340             return STATUS_SUCCESS;
1341         }
1342         FIXME( "ZeroTlsCell not supported on other threads\n" );
1343         return STATUS_NOT_IMPLEMENTED;
1344
1345     case ThreadImpersonationToken:
1346         {
1347             const HANDLE *phToken = data;
1348             if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1349             TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1350             SERVER_START_REQ( set_thread_info )
1351             {
1352                 req->handle   = handle;
1353                 req->token    = *phToken;
1354                 req->mask     = SET_THREAD_INFO_TOKEN;
1355                 status = wine_server_call( req );
1356             }
1357             SERVER_END_REQ;
1358         }
1359         return status;
1360     case ThreadBasePriority:
1361         {
1362             const DWORD *pprio = data;
1363             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1364             SERVER_START_REQ( set_thread_info )
1365             {
1366                 req->handle   = handle;
1367                 req->priority = *pprio;
1368                 req->mask     = SET_THREAD_INFO_PRIORITY;
1369                 status = wine_server_call( req );
1370             }
1371             SERVER_END_REQ;
1372         }
1373         return status;
1374     case ThreadAffinityMask:
1375         {
1376             const DWORD *paff = data;
1377             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1378             SERVER_START_REQ( set_thread_info )
1379             {
1380                 req->handle   = handle;
1381                 req->affinity = *paff;
1382                 req->mask     = SET_THREAD_INFO_AFFINITY;
1383                 status = wine_server_call( req );
1384             }
1385             SERVER_END_REQ;
1386         }
1387         return status;
1388     case ThreadBasicInformation:
1389     case ThreadTimes:
1390     case ThreadPriority:
1391     case ThreadDescriptorTableEntry:
1392     case ThreadEnableAlignmentFaultFixup:
1393     case ThreadEventPair_Reusable:
1394     case ThreadQuerySetWin32StartAddress:
1395     case ThreadPerformanceCount:
1396     case ThreadAmILastThread:
1397     case ThreadIdealProcessor:
1398     case ThreadPriorityBoost:
1399     case ThreadSetTlsArrayAddress:
1400     case ThreadIsIoPending:
1401     default:
1402         FIXME( "info class %d not supported yet\n", class );
1403         return STATUS_NOT_IMPLEMENTED;
1404     }
1405 }
1406
1407
1408 /**********************************************************************
1409  *           NtCurrentTeb   (NTDLL.@)
1410  */
1411 #if defined(__i386__) && defined(__GNUC__)
1412
1413 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1414
1415 #elif defined(__i386__) && defined(_MSC_VER)
1416
1417 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1418
1419 #else
1420
1421 /**********************************************************************/
1422
1423 TEB * WINAPI NtCurrentTeb(void)
1424 {
1425     return pthread_functions.get_current_teb();
1426 }
1427
1428 #endif  /* __i386__ */