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