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