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