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