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