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