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