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