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