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