ntdll: Abuse RtlCreateUserThread to call the thread function for CreateThread directly.
[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( ! is_current_process( process ) )
477     {
478         ERR("Unsupported on other process\n");
479         return STATUS_ACCESS_DENIED;
480     }
481
482     if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
483     fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
484     wine_server_send_fd( request_pipe[0] );
485
486     SERVER_START_REQ( new_thread )
487     {
488         req->access     = THREAD_ALL_ACCESS;
489         req->attributes = 0;  /* FIXME */
490         req->suspend    = suspended;
491         req->request_fd = request_pipe[0];
492         if (!(status = wine_server_call( req )))
493         {
494             handle = reply->handle;
495             tid = reply->tid;
496         }
497         close( request_pipe[0] );
498     }
499     SERVER_END_REQ;
500
501     if (status)
502     {
503         close( request_pipe[1] );
504         return status;
505     }
506
507     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
508
509     addr = NULL;
510     size = sigstack_total_size;
511     if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
512                                            &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
513         goto error;
514     teb = addr;
515     teb->Peb = NtCurrentTeb()->Peb;
516     info = (struct startup_info *)(teb + 1);
517     info->pthread_info.teb_size = size;
518     if ((status = init_teb( teb ))) goto error;
519
520     teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
521     teb->ClientId.UniqueThread  = (HANDLE)tid;
522
523     thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
524     thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
525     thread_data->request_fd  = request_pipe[1];
526
527     info->pthread_info.teb_base = teb;
528     info->pthread_info.teb_sel  = thread_regs->fs;
529
530     /* inherit debug registers from parent thread */
531     thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
532     thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
533     thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
534     thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
535     thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
536     thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
537
538     if (!stack_reserve || !stack_commit)
539     {
540         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
541         if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
542         if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
543     }
544     if (stack_reserve < stack_commit) stack_reserve = stack_commit;
545     stack_reserve += page_size;  /* for the guard page */
546     stack_reserve = (stack_reserve + 0xffff) & ~0xffff;  /* round to 64K boundary */
547     if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024;  /* Xlib needs a large stack */
548
549     info->pthread_info.stack_base = NULL;
550     info->pthread_info.stack_size = stack_reserve;
551     info->pthread_info.entry      = start_thread;
552     info->entry_point             = start;
553     info->entry_arg               = param;
554
555     if (pthread_functions.create_thread( &info->pthread_info ) == -1)
556     {
557         status = STATUS_NO_MEMORY;
558         goto error;
559     }
560     pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
561
562     if (id) id->UniqueThread = (HANDLE)tid;
563     if (handle_ptr) *handle_ptr = handle;
564     else NtClose( handle );
565
566     return STATUS_SUCCESS;
567
568 error:
569     if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
570     if (addr)
571     {
572         SIZE_T size = 0;
573         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
574     }
575     if (handle) NtClose( handle );
576     pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
577     close( request_pipe[1] );
578     return status;
579 }
580
581
582 /***********************************************************************
583  *           RtlExitUserThread  (NTDLL.@)
584  */
585 void WINAPI RtlExitUserThread( ULONG status )
586 {
587     LdrShutdownThread();
588     server_exit_thread( status );
589 }
590
591
592 /***********************************************************************
593  *              NtOpenThread   (NTDLL.@)
594  *              ZwOpenThread   (NTDLL.@)
595  */
596 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
597                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
598 {
599     NTSTATUS ret;
600
601     SERVER_START_REQ( open_thread )
602     {
603         req->tid        = (thread_id_t)id->UniqueThread;
604         req->access     = access;
605         req->attributes = attr ? attr->Attributes : 0;
606         ret = wine_server_call( req );
607         *handle = reply->handle;
608     }
609     SERVER_END_REQ;
610     return ret;
611 }
612
613
614 /******************************************************************************
615  *              NtSuspendThread   (NTDLL.@)
616  *              ZwSuspendThread   (NTDLL.@)
617  */
618 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
619 {
620     NTSTATUS ret;
621
622     SERVER_START_REQ( suspend_thread )
623     {
624         req->handle = handle;
625         if (!(ret = wine_server_call( req ))) *count = reply->count;
626     }
627     SERVER_END_REQ;
628     return ret;
629 }
630
631
632 /******************************************************************************
633  *              NtResumeThread   (NTDLL.@)
634  *              ZwResumeThread   (NTDLL.@)
635  */
636 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
637 {
638     NTSTATUS ret;
639
640     SERVER_START_REQ( resume_thread )
641     {
642         req->handle = handle;
643         if (!(ret = wine_server_call( req ))) *count = reply->count;
644     }
645     SERVER_END_REQ;
646     return ret;
647 }
648
649
650 /******************************************************************************
651  *              NtAlertResumeThread   (NTDLL.@)
652  *              ZwAlertResumeThread   (NTDLL.@)
653  */
654 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
655 {
656     FIXME( "stub: should alert thread %p\n", handle );
657     return NtResumeThread( handle, count );
658 }
659
660
661 /******************************************************************************
662  *              NtAlertThread   (NTDLL.@)
663  *              ZwAlertThread   (NTDLL.@)
664  */
665 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
666 {
667     FIXME( "stub: %p\n", handle );
668     return STATUS_NOT_IMPLEMENTED;
669 }
670
671
672 /******************************************************************************
673  *              NtTerminateThread  (NTDLL.@)
674  *              ZwTerminateThread  (NTDLL.@)
675  */
676 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
677 {
678     NTSTATUS ret;
679     BOOL self, last;
680
681     SERVER_START_REQ( terminate_thread )
682     {
683         req->handle    = handle;
684         req->exit_code = exit_code;
685         ret = wine_server_call( req );
686         self = !ret && reply->self;
687         last = reply->last;
688     }
689     SERVER_END_REQ;
690
691     if (self)
692     {
693         if (last) exit( exit_code );
694         else server_abort_thread( exit_code );
695     }
696     return ret;
697 }
698
699
700 /******************************************************************************
701  *              NtQueueApcThread  (NTDLL.@)
702  */
703 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
704                                   ULONG_PTR arg2, ULONG_PTR arg3 )
705 {
706     NTSTATUS ret;
707     SERVER_START_REQ( queue_apc )
708     {
709         req->thread = handle;
710         if (func)
711         {
712             req->call.type         = APC_USER;
713             req->call.user.func    = func;
714             req->call.user.args[0] = arg1;
715             req->call.user.args[1] = arg2;
716             req->call.user.args[2] = arg3;
717         }
718         else req->call.type = APC_NONE;  /* wake up only */
719         ret = wine_server_call( req );
720     }
721     SERVER_END_REQ;
722     return ret;
723 }
724
725
726 /***********************************************************************
727  *              NtSetContextThread  (NTDLL.@)
728  *              ZwSetContextThread  (NTDLL.@)
729  */
730 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
731 {
732     NTSTATUS ret;
733     DWORD dummy, i;
734     BOOL self = FALSE;
735
736 #ifdef __i386__
737     /* on i386 debug registers always require a server call */
738     self = (handle == GetCurrentThread());
739     if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
740     {
741         struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
742         self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
743                 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
744                 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
745     }
746 #endif
747
748     if (!self)
749     {
750         SERVER_START_REQ( set_thread_context )
751         {
752             req->handle  = handle;
753             req->flags   = context->ContextFlags;
754             req->suspend = 0;
755             wine_server_add_data( req, context, sizeof(*context) );
756             ret = wine_server_call( req );
757             self = reply->self;
758         }
759         SERVER_END_REQ;
760
761         if (ret == STATUS_PENDING)
762         {
763             if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
764             {
765                 for (i = 0; i < 100; i++)
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                     }
775                     SERVER_END_REQ;
776                     if (ret != STATUS_PENDING) break;
777                     NtYieldExecution();
778                 }
779                 NtResumeThread( handle, &dummy );
780             }
781             if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
782         }
783
784         if (ret) return ret;
785     }
786
787     if (self) set_cpu_context( context );
788     return STATUS_SUCCESS;
789 }
790
791
792 /* copy a context structure according to the flags */
793 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
794 {
795 #ifdef __i386__
796     flags &= ~CONTEXT_i386;  /* get rid of CPU id */
797     if (flags & CONTEXT_INTEGER)
798     {
799         to->Eax = from->Eax;
800         to->Ebx = from->Ebx;
801         to->Ecx = from->Ecx;
802         to->Edx = from->Edx;
803         to->Esi = from->Esi;
804         to->Edi = from->Edi;
805     }
806     if (flags & CONTEXT_CONTROL)
807     {
808         to->Ebp    = from->Ebp;
809         to->Esp    = from->Esp;
810         to->Eip    = from->Eip;
811         to->SegCs  = from->SegCs;
812         to->SegSs  = from->SegSs;
813         to->EFlags = from->EFlags;
814     }
815     if (flags & CONTEXT_SEGMENTS)
816     {
817         to->SegDs = from->SegDs;
818         to->SegEs = from->SegEs;
819         to->SegFs = from->SegFs;
820         to->SegGs = from->SegGs;
821     }
822     if (flags & CONTEXT_DEBUG_REGISTERS)
823     {
824         to->Dr0 = from->Dr0;
825         to->Dr1 = from->Dr1;
826         to->Dr2 = from->Dr2;
827         to->Dr3 = from->Dr3;
828         to->Dr6 = from->Dr6;
829         to->Dr7 = from->Dr7;
830     }
831     if (flags & CONTEXT_FLOATING_POINT)
832     {
833         to->FloatSave = from->FloatSave;
834     }
835 #elif defined(__x86_64__)
836     flags &= ~CONTEXT_AMD64;  /* get rid of CPU id */
837     if (flags & CONTEXT_CONTROL)
838     {
839         to->Rbp    = from->Rbp;
840         to->Rip    = from->Rip;
841         to->Rsp    = from->Rsp;
842         to->SegCs  = from->SegCs;
843         to->SegSs  = from->SegSs;
844         to->EFlags = from->EFlags;
845         to->MxCsr  = from->MxCsr;
846     }
847     if (flags & CONTEXT_INTEGER)
848     {
849         to->Rax = from->Rax;
850         to->Rcx = from->Rcx;
851         to->Rdx = from->Rdx;
852         to->Rbx = from->Rbx;
853         to->Rsi = from->Rsi;
854         to->Rdi = from->Rdi;
855         to->R8  = from->R8;
856         to->R9  = from->R9;
857         to->R10 = from->R10;
858         to->R11 = from->R11;
859         to->R12 = from->R12;
860         to->R13 = from->R13;
861         to->R14 = from->R14;
862         to->R15 = from->R15;
863     }
864     if (flags & CONTEXT_SEGMENTS)
865     {
866         to->SegDs = from->SegDs;
867         to->SegEs = from->SegEs;
868         to->SegFs = from->SegFs;
869         to->SegGs = from->SegGs;
870     }
871     if (flags & CONTEXT_FLOATING_POINT)
872     {
873         to->u.FltSave = from->u.FltSave;
874     }
875     if (flags & CONTEXT_DEBUG_REGISTERS)
876     {
877         to->Dr0 = from->Dr0;
878         to->Dr1 = from->Dr1;
879         to->Dr2 = from->Dr2;
880         to->Dr3 = from->Dr3;
881         to->Dr6 = from->Dr6;
882         to->Dr7 = from->Dr7;
883     }
884 #elif defined(__sparc__)
885     flags &= ~CONTEXT_SPARC;  /* get rid of CPU id */
886     if (flags & CONTEXT_CONTROL)
887     {
888         to->psr = from->psr;
889         to->pc  = from->pc;
890         to->npc = from->npc;
891         to->y   = from->y;
892         to->wim = from->wim;
893         to->tbr = from->tbr;
894     }
895     if (flags & CONTEXT_INTEGER)
896     {
897         to->g0 = from->g0;
898         to->g1 = from->g1;
899         to->g2 = from->g2;
900         to->g3 = from->g3;
901         to->g4 = from->g4;
902         to->g5 = from->g5;
903         to->g6 = from->g6;
904         to->g7 = from->g7;
905         to->o0 = from->o0;
906         to->o1 = from->o1;
907         to->o2 = from->o2;
908         to->o3 = from->o3;
909         to->o4 = from->o4;
910         to->o5 = from->o5;
911         to->o6 = from->o6;
912         to->o7 = from->o7;
913         to->l0 = from->l0;
914         to->l1 = from->l1;
915         to->l2 = from->l2;
916         to->l3 = from->l3;
917         to->l4 = from->l4;
918         to->l5 = from->l5;
919         to->l6 = from->l6;
920         to->l7 = from->l7;
921         to->i0 = from->i0;
922         to->i1 = from->i1;
923         to->i2 = from->i2;
924         to->i3 = from->i3;
925         to->i4 = from->i4;
926         to->i5 = from->i5;
927         to->i6 = from->i6;
928         to->i7 = from->i7;
929     }
930     if (flags & CONTEXT_FLOATING_POINT)
931     {
932         /* FIXME */
933     }
934 #elif defined(__powerpc__)
935     /* Has no CPU id */
936     if (flags & CONTEXT_CONTROL)
937     {
938         to->Msr = from->Msr;
939         to->Ctr = from->Ctr;
940         to->Iar = from->Iar;
941     }
942     if (flags & CONTEXT_INTEGER)
943     {
944         to->Gpr0  = from->Gpr0;
945         to->Gpr1  = from->Gpr1;
946         to->Gpr2  = from->Gpr2;
947         to->Gpr3  = from->Gpr3;
948         to->Gpr4  = from->Gpr4;
949         to->Gpr5  = from->Gpr5;
950         to->Gpr6  = from->Gpr6;
951         to->Gpr7  = from->Gpr7;
952         to->Gpr8  = from->Gpr8;
953         to->Gpr9  = from->Gpr9;
954         to->Gpr10 = from->Gpr10;
955         to->Gpr11 = from->Gpr11;
956         to->Gpr12 = from->Gpr12;
957         to->Gpr13 = from->Gpr13;
958         to->Gpr14 = from->Gpr14;
959         to->Gpr15 = from->Gpr15;
960         to->Gpr16 = from->Gpr16;
961         to->Gpr17 = from->Gpr17;
962         to->Gpr18 = from->Gpr18;
963         to->Gpr19 = from->Gpr19;
964         to->Gpr20 = from->Gpr20;
965         to->Gpr21 = from->Gpr21;
966         to->Gpr22 = from->Gpr22;
967         to->Gpr23 = from->Gpr23;
968         to->Gpr24 = from->Gpr24;
969         to->Gpr25 = from->Gpr25;
970         to->Gpr26 = from->Gpr26;
971         to->Gpr27 = from->Gpr27;
972         to->Gpr28 = from->Gpr28;
973         to->Gpr29 = from->Gpr29;
974         to->Gpr30 = from->Gpr30;
975         to->Gpr31 = from->Gpr31;
976         to->Xer   = from->Xer;
977         to->Cr    = from->Cr;
978     }
979     if (flags & CONTEXT_FLOATING_POINT)
980     {
981         to->Fpr0  = from->Fpr0;
982         to->Fpr1  = from->Fpr1;
983         to->Fpr2  = from->Fpr2;
984         to->Fpr3  = from->Fpr3;
985         to->Fpr4  = from->Fpr4;
986         to->Fpr5  = from->Fpr5;
987         to->Fpr6  = from->Fpr6;
988         to->Fpr7  = from->Fpr7;
989         to->Fpr8  = from->Fpr8;
990         to->Fpr9  = from->Fpr9;
991         to->Fpr10 = from->Fpr10;
992         to->Fpr11 = from->Fpr11;
993         to->Fpr12 = from->Fpr12;
994         to->Fpr13 = from->Fpr13;
995         to->Fpr14 = from->Fpr14;
996         to->Fpr15 = from->Fpr15;
997         to->Fpr16 = from->Fpr16;
998         to->Fpr17 = from->Fpr17;
999         to->Fpr18 = from->Fpr18;
1000         to->Fpr19 = from->Fpr19;
1001         to->Fpr20 = from->Fpr20;
1002         to->Fpr21 = from->Fpr21;
1003         to->Fpr22 = from->Fpr22;
1004         to->Fpr23 = from->Fpr23;
1005         to->Fpr24 = from->Fpr24;
1006         to->Fpr25 = from->Fpr25;
1007         to->Fpr26 = from->Fpr26;
1008         to->Fpr27 = from->Fpr27;
1009         to->Fpr28 = from->Fpr28;
1010         to->Fpr29 = from->Fpr29;
1011         to->Fpr30 = from->Fpr30;
1012         to->Fpr31 = from->Fpr31;
1013         to->Fpscr = from->Fpscr;
1014     }
1015 #else
1016 #error You must implement context copying for your CPU
1017 #endif
1018 }
1019
1020
1021 /***********************************************************************
1022  *              NtGetContextThread  (NTDLL.@)
1023  *              ZwGetContextThread  (NTDLL.@)
1024  */
1025 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1026 {
1027     NTSTATUS ret;
1028     CONTEXT ctx;
1029     DWORD dummy, i;
1030     DWORD needed_flags = context->ContextFlags;
1031     BOOL self = (handle == GetCurrentThread());
1032
1033 #ifdef __i386__
1034     /* on i386 debug registers always require a server call */
1035     if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1036 #endif
1037
1038     if (!self)
1039     {
1040         SERVER_START_REQ( get_thread_context )
1041         {
1042             req->handle  = handle;
1043             req->flags   = context->ContextFlags;
1044             req->suspend = 0;
1045             wine_server_set_reply( req, &ctx, sizeof(ctx) );
1046             ret = wine_server_call( req );
1047             self = reply->self;
1048         }
1049         SERVER_END_REQ;
1050
1051         if (ret == STATUS_PENDING)
1052         {
1053             if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1054             {
1055                 for (i = 0; i < 100; i++)
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                     }
1065                     SERVER_END_REQ;
1066                     if (ret != STATUS_PENDING) break;
1067                     NtYieldExecution();
1068                 }
1069                 NtResumeThread( handle, &dummy );
1070             }
1071             if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1072         }
1073         if (ret) return ret;
1074         copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1075         needed_flags &= ~ctx.ContextFlags;
1076     }
1077
1078     if (self)
1079     {
1080         if (needed_flags)
1081         {
1082             get_cpu_context( &ctx );
1083             copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1084         }
1085 #ifdef __i386__
1086         /* update the cached version of the debug registers */
1087         if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1088         {
1089             struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1090             regs->dr0 = context->Dr0;
1091             regs->dr1 = context->Dr1;
1092             regs->dr2 = context->Dr2;
1093             regs->dr3 = context->Dr3;
1094             regs->dr6 = context->Dr6;
1095             regs->dr7 = context->Dr7;
1096         }
1097 #endif
1098     }
1099     return STATUS_SUCCESS;
1100 }
1101
1102
1103 /******************************************************************************
1104  *              NtQueryInformationThread  (NTDLL.@)
1105  *              ZwQueryInformationThread  (NTDLL.@)
1106  */
1107 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1108                                           void *data, ULONG length, ULONG *ret_len )
1109 {
1110     NTSTATUS status;
1111
1112     switch(class)
1113     {
1114     case ThreadBasicInformation:
1115         {
1116             THREAD_BASIC_INFORMATION info;
1117
1118             SERVER_START_REQ( get_thread_info )
1119             {
1120                 req->handle = handle;
1121                 req->tid_in = 0;
1122                 if (!(status = wine_server_call( req )))
1123                 {
1124                     info.ExitStatus             = reply->exit_code;
1125                     info.TebBaseAddress         = reply->teb;
1126                     info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1127                     info.ClientId.UniqueThread  = (HANDLE)reply->tid;
1128                     info.AffinityMask           = reply->affinity;
1129                     info.Priority               = reply->priority;
1130                     info.BasePriority           = reply->priority;  /* FIXME */
1131                 }
1132             }
1133             SERVER_END_REQ;
1134             if (status == STATUS_SUCCESS)
1135             {
1136                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1137                 if (ret_len) *ret_len = min( length, sizeof(info) );
1138             }
1139         }
1140         return status;
1141     case ThreadTimes:
1142         {
1143             KERNEL_USER_TIMES   kusrt;
1144             /* We need to do a server call to get the creation time or exit time */
1145             /* This works on any thread */
1146             SERVER_START_REQ( get_thread_info )
1147             {
1148                 req->handle = handle;
1149                 req->tid_in = 0;
1150                 status = wine_server_call( req );
1151                 if (status == STATUS_SUCCESS)
1152                 {
1153                     NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1154                     NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1155                 }
1156             }
1157             SERVER_END_REQ;
1158             if (status == STATUS_SUCCESS)
1159             {
1160                 /* We call times(2) for kernel time or user time */
1161                 /* We can only (portably) do this for the current thread */
1162                 if (handle == GetCurrentThread())
1163                 {
1164                     struct tms time_buf;
1165                     long clocks_per_sec = sysconf(_SC_CLK_TCK);
1166
1167                     times(&time_buf);
1168                     kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1169                     kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1170                 }
1171                 else
1172                 {
1173                     kusrt.KernelTime.QuadPart = 0;
1174                     kusrt.UserTime.QuadPart = 0;
1175                     FIXME("Cannot get kerneltime or usertime of other threads\n");
1176                 }
1177                 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1178                 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1179             }
1180         }
1181         return status;
1182     case ThreadDescriptorTableEntry:
1183         {
1184 #ifdef __i386__
1185             THREAD_DESCRIPTOR_INFORMATION*      tdi = data;
1186             if (length < sizeof(*tdi))
1187                 status = STATUS_INFO_LENGTH_MISMATCH;
1188             else if (!(tdi->Selector & 4))  /* GDT selector */
1189             {
1190                 unsigned sel = tdi->Selector & ~3;  /* ignore RPL */
1191                 status = STATUS_SUCCESS;
1192                 if (!sel)  /* null selector */
1193                     memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1194                 else
1195                 {
1196                     tdi->Entry.BaseLow                   = 0;
1197                     tdi->Entry.HighWord.Bits.BaseMid     = 0;
1198                     tdi->Entry.HighWord.Bits.BaseHi      = 0;
1199                     tdi->Entry.LimitLow                  = 0xffff;
1200                     tdi->Entry.HighWord.Bits.LimitHi     = 0xf;
1201                     tdi->Entry.HighWord.Bits.Dpl         = 3;
1202                     tdi->Entry.HighWord.Bits.Sys         = 0;
1203                     tdi->Entry.HighWord.Bits.Pres        = 1;
1204                     tdi->Entry.HighWord.Bits.Granularity = 1;
1205                     tdi->Entry.HighWord.Bits.Default_Big = 1;
1206                     tdi->Entry.HighWord.Bits.Type        = 0x12;
1207                     /* it has to be one of the system GDT selectors */
1208                     if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1209                     {
1210                         if (sel == (wine_get_cs() & ~3))
1211                             tdi->Entry.HighWord.Bits.Type |= 8;  /* code segment */
1212                         else status = STATUS_ACCESS_DENIED;
1213                     }
1214                 }
1215             }
1216             else
1217             {
1218                 SERVER_START_REQ( get_selector_entry )
1219                 {
1220                     req->handle = handle;
1221                     req->entry = tdi->Selector >> 3;
1222                     status = wine_server_call( req );
1223                     if (!status)
1224                     {
1225                         if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1226                             status = STATUS_ACCESS_VIOLATION;
1227                         else
1228                         {
1229                             wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1230                             wine_ldt_set_limit( &tdi->Entry, reply->limit );
1231                             wine_ldt_set_flags( &tdi->Entry, reply->flags );
1232                         }
1233                     }
1234                 }
1235                 SERVER_END_REQ;
1236             }
1237             if (status == STATUS_SUCCESS && ret_len)
1238                 /* yes, that's a bit strange, but it's the way it is */
1239                 *ret_len = sizeof(LDT_ENTRY);
1240 #else
1241             status = STATUS_NOT_IMPLEMENTED;
1242 #endif
1243             return status;
1244         }
1245     case ThreadAmILastThread:
1246         {
1247             SERVER_START_REQ(get_thread_info)
1248             {
1249                 req->handle = handle;
1250                 req->tid_in = 0;
1251                 status = wine_server_call( req );
1252                 if (status == STATUS_SUCCESS)
1253                 {
1254                     BOOLEAN last = reply->last;
1255                     if (data) memcpy( data, &last, min( length, sizeof(last) ));
1256                     if (ret_len) *ret_len = min( length, sizeof(last) );
1257                 }
1258             }
1259             SERVER_END_REQ;
1260             return status;
1261         }
1262     case ThreadPriority:
1263     case ThreadBasePriority:
1264     case ThreadAffinityMask:
1265     case ThreadImpersonationToken:
1266     case ThreadEnableAlignmentFaultFixup:
1267     case ThreadEventPair_Reusable:
1268     case ThreadQuerySetWin32StartAddress:
1269     case ThreadZeroTlsCell:
1270     case ThreadPerformanceCount:
1271     case ThreadIdealProcessor:
1272     case ThreadPriorityBoost:
1273     case ThreadSetTlsArrayAddress:
1274     case ThreadIsIoPending:
1275     default:
1276         FIXME( "info class %d not supported yet\n", class );
1277         return STATUS_NOT_IMPLEMENTED;
1278     }
1279 }
1280
1281
1282 /******************************************************************************
1283  *              NtSetInformationThread  (NTDLL.@)
1284  *              ZwSetInformationThread  (NTDLL.@)
1285  */
1286 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1287                                         LPCVOID data, ULONG length )
1288 {
1289     NTSTATUS status;
1290     switch(class)
1291     {
1292     case ThreadZeroTlsCell:
1293         if (handle == GetCurrentThread())
1294         {
1295             LIST_ENTRY *entry;
1296             DWORD index;
1297
1298             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1299             index = *(const DWORD *)data;
1300             if (index < TLS_MINIMUM_AVAILABLE)
1301             {
1302                 RtlAcquirePebLock();
1303                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1304                 {
1305                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1306                     teb->TlsSlots[index] = 0;
1307                 }
1308                 RtlReleasePebLock();
1309             }
1310             else
1311             {
1312                 index -= TLS_MINIMUM_AVAILABLE;
1313                 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1314                     return STATUS_INVALID_PARAMETER;
1315                 RtlAcquirePebLock();
1316                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1317                 {
1318                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1319                     if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1320                 }
1321                 RtlReleasePebLock();
1322             }
1323             return STATUS_SUCCESS;
1324         }
1325         FIXME( "ZeroTlsCell not supported on other threads\n" );
1326         return STATUS_NOT_IMPLEMENTED;
1327
1328     case ThreadImpersonationToken:
1329         {
1330             const HANDLE *phToken = data;
1331             if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1332             TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1333             SERVER_START_REQ( set_thread_info )
1334             {
1335                 req->handle   = handle;
1336                 req->token    = *phToken;
1337                 req->mask     = SET_THREAD_INFO_TOKEN;
1338                 status = wine_server_call( req );
1339             }
1340             SERVER_END_REQ;
1341         }
1342         return status;
1343     case ThreadBasePriority:
1344         {
1345             const DWORD *pprio = data;
1346             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1347             SERVER_START_REQ( set_thread_info )
1348             {
1349                 req->handle   = handle;
1350                 req->priority = *pprio;
1351                 req->mask     = SET_THREAD_INFO_PRIORITY;
1352                 status = wine_server_call( req );
1353             }
1354             SERVER_END_REQ;
1355         }
1356         return status;
1357     case ThreadAffinityMask:
1358         {
1359             const DWORD *paff = data;
1360             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1361             SERVER_START_REQ( set_thread_info )
1362             {
1363                 req->handle   = handle;
1364                 req->affinity = *paff;
1365                 req->mask     = SET_THREAD_INFO_AFFINITY;
1366                 status = wine_server_call( req );
1367             }
1368             SERVER_END_REQ;
1369         }
1370         return status;
1371     case ThreadBasicInformation:
1372     case ThreadTimes:
1373     case ThreadPriority:
1374     case ThreadDescriptorTableEntry:
1375     case ThreadEnableAlignmentFaultFixup:
1376     case ThreadEventPair_Reusable:
1377     case ThreadQuerySetWin32StartAddress:
1378     case ThreadPerformanceCount:
1379     case ThreadAmILastThread:
1380     case ThreadIdealProcessor:
1381     case ThreadPriorityBoost:
1382     case ThreadSetTlsArrayAddress:
1383     case ThreadIsIoPending:
1384     default:
1385         FIXME( "info class %d not supported yet\n", class );
1386         return STATUS_NOT_IMPLEMENTED;
1387     }
1388 }
1389
1390
1391 /**********************************************************************
1392  *           NtCurrentTeb   (NTDLL.@)
1393  */
1394 #if defined(__i386__) && defined(__GNUC__)
1395
1396 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1397
1398 #elif defined(__i386__) && defined(_MSC_VER)
1399
1400 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1401
1402 #else
1403
1404 /**********************************************************************/
1405
1406 TEB * WINAPI NtCurrentTeb(void)
1407 {
1408     return pthread_functions.get_current_teb();
1409 }
1410
1411 #endif  /* __i386__ */