riched20: Initial support for word break callback procedures.
[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     thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
298     thread_data->request_fd  = request_pipe[1];
299
300     info->pthread_info.teb_base = teb;
301     info->pthread_info.teb_sel  = thread_data->teb_sel;
302
303     if (!stack_reserve || !stack_commit)
304     {
305         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
306         if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
307         if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
308     }
309     if (stack_reserve < stack_commit) stack_reserve = stack_commit;
310     stack_reserve += page_size;  /* for the guard page */
311     stack_reserve = (stack_reserve + 0xffff) & ~0xffff;  /* round to 64K boundary */
312     if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024;  /* Xlib needs a large stack */
313
314     info->pthread_info.stack_base = NULL;
315     info->pthread_info.stack_size = stack_reserve;
316     info->pthread_info.entry      = start_thread;
317     info->entry_point             = start;
318     info->entry_arg               = param;
319
320     if (pthread_functions.create_thread( &info->pthread_info ) == -1)
321     {
322         status = STATUS_NO_MEMORY;
323         goto error;
324     }
325
326     if (id) id->UniqueThread = (HANDLE)tid;
327     if (handle_ptr) *handle_ptr = handle;
328     else NtClose( handle );
329
330     return STATUS_SUCCESS;
331
332 error:
333     if (thread_data) wine_ldt_free_fs( thread_data->teb_sel );
334     if (addr)
335     {
336         SIZE_T size = 0;
337         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
338     }
339     if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
340     if (handle) NtClose( handle );
341     close( request_pipe[1] );
342     return status;
343 }
344
345
346 /***********************************************************************
347  *           RtlExitUserThread  (NTDLL.@)
348  */
349 void WINAPI RtlExitUserThread( ULONG status )
350 {
351     LdrShutdownThread();
352     server_exit_thread( status );
353 }
354
355
356 /***********************************************************************
357  *              NtOpenThread   (NTDLL.@)
358  *              ZwOpenThread   (NTDLL.@)
359  */
360 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
361                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
362 {
363     NTSTATUS ret;
364
365     SERVER_START_REQ( open_thread )
366     {
367         req->tid        = (thread_id_t)id->UniqueThread;
368         req->access     = access;
369         req->attributes = attr ? attr->Attributes : 0;
370         ret = wine_server_call( req );
371         *handle = reply->handle;
372     }
373     SERVER_END_REQ;
374     return ret;
375 }
376
377
378 /******************************************************************************
379  *              NtSuspendThread   (NTDLL.@)
380  *              ZwSuspendThread   (NTDLL.@)
381  */
382 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
383 {
384     NTSTATUS ret;
385
386     SERVER_START_REQ( suspend_thread )
387     {
388         req->handle = handle;
389         if (!(ret = wine_server_call( req ))) *count = reply->count;
390     }
391     SERVER_END_REQ;
392     return ret;
393 }
394
395
396 /******************************************************************************
397  *              NtResumeThread   (NTDLL.@)
398  *              ZwResumeThread   (NTDLL.@)
399  */
400 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
401 {
402     NTSTATUS ret;
403
404     SERVER_START_REQ( resume_thread )
405     {
406         req->handle = handle;
407         if (!(ret = wine_server_call( req ))) *count = reply->count;
408     }
409     SERVER_END_REQ;
410     return ret;
411 }
412
413
414 /******************************************************************************
415  *              NtAlertResumeThread   (NTDLL.@)
416  *              ZwAlertResumeThread   (NTDLL.@)
417  */
418 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
419 {
420     FIXME( "stub: should alert thread %p\n", handle );
421     return NtResumeThread( handle, count );
422 }
423
424
425 /******************************************************************************
426  *              NtAlertThread   (NTDLL.@)
427  *              ZwAlertThread   (NTDLL.@)
428  */
429 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
430 {
431     FIXME( "stub: %p\n", handle );
432     return STATUS_NOT_IMPLEMENTED;
433 }
434
435
436 /******************************************************************************
437  *              NtTerminateThread  (NTDLL.@)
438  *              ZwTerminateThread  (NTDLL.@)
439  */
440 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
441 {
442     NTSTATUS ret;
443     BOOL self, last;
444
445     SERVER_START_REQ( terminate_thread )
446     {
447         req->handle    = handle;
448         req->exit_code = exit_code;
449         ret = wine_server_call( req );
450         self = !ret && reply->self;
451         last = reply->last;
452     }
453     SERVER_END_REQ;
454
455     if (self)
456     {
457         if (last) exit( exit_code );
458         else server_abort_thread( exit_code );
459     }
460     return ret;
461 }
462
463
464 /******************************************************************************
465  *              NtQueueApcThread  (NTDLL.@)
466  */
467 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
468                                   ULONG_PTR arg2, ULONG_PTR arg3 )
469 {
470     NTSTATUS ret;
471     SERVER_START_REQ( queue_apc )
472     {
473         req->handle = handle;
474         req->user   = 1;
475         req->func   = func;
476         req->arg1   = (void *)arg1;
477         req->arg2   = (void *)arg2;
478         req->arg3   = (void *)arg3;
479         ret = wine_server_call( req );
480     }
481     SERVER_END_REQ;
482     return ret;
483 }
484
485
486 /***********************************************************************
487  *              NtSetContextThread  (NTDLL.@)
488  *              ZwSetContextThread  (NTDLL.@)
489  */
490 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
491 {
492     NTSTATUS ret;
493     DWORD dummy, i;
494     BOOL self = FALSE;
495
496 #ifdef __i386__
497     /* on i386 debug registers always require a server call */
498     self = ((handle == GetCurrentThread()) &&
499             !(context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)));
500 #endif
501
502     if (!self)
503     {
504         SERVER_START_REQ( set_thread_context )
505         {
506             req->handle  = handle;
507             req->flags   = context->ContextFlags;
508             req->suspend = 0;
509             wine_server_add_data( req, context, sizeof(*context) );
510             ret = wine_server_call( req );
511             self = reply->self;
512         }
513         SERVER_END_REQ;
514
515         if (ret == STATUS_PENDING)
516         {
517             if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
518             {
519                 for (i = 0; i < 100; i++)
520                 {
521                     SERVER_START_REQ( set_thread_context )
522                     {
523                         req->handle  = handle;
524                         req->flags   = context->ContextFlags;
525                         req->suspend = 0;
526                         wine_server_add_data( req, context, sizeof(*context) );
527                         ret = wine_server_call( req );
528                     }
529                     SERVER_END_REQ;
530                     if (ret != STATUS_PENDING) break;
531                     NtYieldExecution();
532                 }
533                 NtResumeThread( handle, &dummy );
534             }
535             if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
536         }
537
538         if (ret) return ret;
539     }
540
541     if (self) set_cpu_context( context );
542     return STATUS_SUCCESS;
543 }
544
545
546 /* copy a context structure according to the flags */
547 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
548 {
549 #ifdef __i386__
550     flags &= ~CONTEXT_i386;  /* get rid of CPU id */
551     if (flags & CONTEXT_INTEGER)
552     {
553         to->Eax = from->Eax;
554         to->Ebx = from->Ebx;
555         to->Ecx = from->Ecx;
556         to->Edx = from->Edx;
557         to->Esi = from->Esi;
558         to->Edi = from->Edi;
559     }
560     if (flags & CONTEXT_CONTROL)
561     {
562         to->Ebp    = from->Ebp;
563         to->Esp    = from->Esp;
564         to->Eip    = from->Eip;
565         to->SegCs  = from->SegCs;
566         to->SegSs  = from->SegSs;
567         to->EFlags = from->EFlags;
568     }
569     if (flags & CONTEXT_SEGMENTS)
570     {
571         to->SegDs = from->SegDs;
572         to->SegEs = from->SegEs;
573         to->SegFs = from->SegFs;
574         to->SegGs = from->SegGs;
575     }
576     if (flags & CONTEXT_DEBUG_REGISTERS)
577     {
578         to->Dr0 = from->Dr0;
579         to->Dr1 = from->Dr1;
580         to->Dr2 = from->Dr2;
581         to->Dr3 = from->Dr3;
582         to->Dr6 = from->Dr6;
583         to->Dr7 = from->Dr7;
584     }
585     if (flags & CONTEXT_FLOATING_POINT)
586     {
587         to->FloatSave = from->FloatSave;
588     }
589 #elif defined(__x86_64__)
590     flags &= ~CONTEXT_AMD64;  /* get rid of CPU id */
591     if (flags & CONTEXT_CONTROL)
592     {
593         to->Rbp    = from->Rbp;
594         to->Rip    = from->Rip;
595         to->Rsp    = from->Rsp;
596         to->SegCs  = from->SegCs;
597         to->SegSs  = from->SegSs;
598         to->EFlags = from->EFlags;
599         to->MxCsr  = from->MxCsr;
600     }
601     if (flags & CONTEXT_INTEGER)
602     {
603         to->Rax = from->Rax;
604         to->Rcx = from->Rcx;
605         to->Rdx = from->Rdx;
606         to->Rbx = from->Rbx;
607         to->Rsi = from->Rsi;
608         to->Rdi = from->Rdi;
609         to->R8  = from->R8;
610         to->R9  = from->R9;
611         to->R10 = from->R10;
612         to->R11 = from->R11;
613         to->R12 = from->R12;
614         to->R13 = from->R13;
615         to->R14 = from->R14;
616         to->R15 = from->R15;
617     }
618     if (flags & CONTEXT_SEGMENTS)
619     {
620         to->SegDs = from->SegDs;
621         to->SegEs = from->SegEs;
622         to->SegFs = from->SegFs;
623         to->SegGs = from->SegGs;
624     }
625     if (flags & CONTEXT_FLOATING_POINT)
626     {
627         to->u.FltSave = from->u.FltSave;
628     }
629     if (flags & CONTEXT_DEBUG_REGISTERS)
630     {
631         to->Dr0 = from->Dr0;
632         to->Dr1 = from->Dr1;
633         to->Dr2 = from->Dr2;
634         to->Dr3 = from->Dr3;
635         to->Dr6 = from->Dr6;
636         to->Dr7 = from->Dr7;
637     }
638 #elif defined(__sparc__)
639     flags &= ~CONTEXT_SPARC;  /* get rid of CPU id */
640     if (flags & CONTEXT_CONTROL)
641     {
642         to->psr = from->psr;
643         to->pc  = from->pc;
644         to->npc = from->npc;
645         to->y   = from->y;
646         to->wim = from->wim;
647         to->tbr = from->tbr;
648     }
649     if (flags & CONTEXT_INTEGER)
650     {
651         to->g0 = from->g0;
652         to->g1 = from->g1;
653         to->g2 = from->g2;
654         to->g3 = from->g3;
655         to->g4 = from->g4;
656         to->g5 = from->g5;
657         to->g6 = from->g6;
658         to->g7 = from->g7;
659         to->o0 = from->o0;
660         to->o1 = from->o1;
661         to->o2 = from->o2;
662         to->o3 = from->o3;
663         to->o4 = from->o4;
664         to->o5 = from->o5;
665         to->o6 = from->o6;
666         to->o7 = from->o7;
667         to->l0 = from->l0;
668         to->l1 = from->l1;
669         to->l2 = from->l2;
670         to->l3 = from->l3;
671         to->l4 = from->l4;
672         to->l5 = from->l5;
673         to->l6 = from->l6;
674         to->l7 = from->l7;
675         to->i0 = from->i0;
676         to->i1 = from->i1;
677         to->i2 = from->i2;
678         to->i3 = from->i3;
679         to->i4 = from->i4;
680         to->i5 = from->i5;
681         to->i6 = from->i6;
682         to->i7 = from->i7;
683     }
684     if (flags & CONTEXT_FLOATING_POINT)
685     {
686         /* FIXME */
687     }
688 #elif defined(__powerpc__)
689     /* Has no CPU id */
690     if (flags & CONTEXT_CONTROL)
691     {
692         to->Msr = from->Msr;
693         to->Ctr = from->Ctr;
694         to->Iar = from->Iar;
695     }
696     if (flags & CONTEXT_INTEGER)
697     {
698         to->Gpr0  = from->Gpr0;
699         to->Gpr1  = from->Gpr1;
700         to->Gpr2  = from->Gpr2;
701         to->Gpr3  = from->Gpr3;
702         to->Gpr4  = from->Gpr4;
703         to->Gpr5  = from->Gpr5;
704         to->Gpr6  = from->Gpr6;
705         to->Gpr7  = from->Gpr7;
706         to->Gpr8  = from->Gpr8;
707         to->Gpr9  = from->Gpr9;
708         to->Gpr10 = from->Gpr10;
709         to->Gpr11 = from->Gpr11;
710         to->Gpr12 = from->Gpr12;
711         to->Gpr13 = from->Gpr13;
712         to->Gpr14 = from->Gpr14;
713         to->Gpr15 = from->Gpr15;
714         to->Gpr16 = from->Gpr16;
715         to->Gpr17 = from->Gpr17;
716         to->Gpr18 = from->Gpr18;
717         to->Gpr19 = from->Gpr19;
718         to->Gpr20 = from->Gpr20;
719         to->Gpr21 = from->Gpr21;
720         to->Gpr22 = from->Gpr22;
721         to->Gpr23 = from->Gpr23;
722         to->Gpr24 = from->Gpr24;
723         to->Gpr25 = from->Gpr25;
724         to->Gpr26 = from->Gpr26;
725         to->Gpr27 = from->Gpr27;
726         to->Gpr28 = from->Gpr28;
727         to->Gpr29 = from->Gpr29;
728         to->Gpr30 = from->Gpr30;
729         to->Gpr31 = from->Gpr31;
730         to->Xer   = from->Xer;
731         to->Cr    = from->Cr;
732     }
733     if (flags & CONTEXT_FLOATING_POINT)
734     {
735         to->Fpr0  = from->Fpr0;
736         to->Fpr1  = from->Fpr1;
737         to->Fpr2  = from->Fpr2;
738         to->Fpr3  = from->Fpr3;
739         to->Fpr4  = from->Fpr4;
740         to->Fpr5  = from->Fpr5;
741         to->Fpr6  = from->Fpr6;
742         to->Fpr7  = from->Fpr7;
743         to->Fpr8  = from->Fpr8;
744         to->Fpr9  = from->Fpr9;
745         to->Fpr10 = from->Fpr10;
746         to->Fpr11 = from->Fpr11;
747         to->Fpr12 = from->Fpr12;
748         to->Fpr13 = from->Fpr13;
749         to->Fpr14 = from->Fpr14;
750         to->Fpr15 = from->Fpr15;
751         to->Fpr16 = from->Fpr16;
752         to->Fpr17 = from->Fpr17;
753         to->Fpr18 = from->Fpr18;
754         to->Fpr19 = from->Fpr19;
755         to->Fpr20 = from->Fpr20;
756         to->Fpr21 = from->Fpr21;
757         to->Fpr22 = from->Fpr22;
758         to->Fpr23 = from->Fpr23;
759         to->Fpr24 = from->Fpr24;
760         to->Fpr25 = from->Fpr25;
761         to->Fpr26 = from->Fpr26;
762         to->Fpr27 = from->Fpr27;
763         to->Fpr28 = from->Fpr28;
764         to->Fpr29 = from->Fpr29;
765         to->Fpr30 = from->Fpr30;
766         to->Fpr31 = from->Fpr31;
767         to->Fpscr = from->Fpscr;
768     }
769 #else
770 #error You must implement context copying for your CPU
771 #endif
772 }
773
774
775 /***********************************************************************
776  *              NtGetContextThread  (NTDLL.@)
777  *              ZwGetContextThread  (NTDLL.@)
778  */
779 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
780 {
781     NTSTATUS ret;
782     CONTEXT ctx;
783     DWORD dummy, i;
784
785     SERVER_START_REQ( get_thread_context )
786     {
787         req->handle  = handle;
788         req->flags   = context->ContextFlags;
789         req->suspend = 0;
790         wine_server_set_reply( req, &ctx, sizeof(ctx) );
791         ret = wine_server_call( req );
792     }
793     SERVER_END_REQ;
794
795     if (ret == STATUS_PENDING)
796     {
797         if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
798         {
799             for (i = 0; i < 100; i++)
800             {
801                 SERVER_START_REQ( get_thread_context )
802                 {
803                     req->handle  = handle;
804                     req->flags   = context->ContextFlags;
805                     req->suspend = 0;
806                     wine_server_set_reply( req, &ctx, sizeof(ctx) );
807                     ret = wine_server_call( req );
808                 }
809                 SERVER_END_REQ;
810                 if (ret != STATUS_PENDING) break;
811                 NtYieldExecution();
812             }
813             NtResumeThread( handle, &dummy );
814         }
815     }
816
817     if (ret == STATUS_SUCCESS) copy_context( context, &ctx, context->ContextFlags );
818     else if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
819     return ret;
820 }
821
822
823 /******************************************************************************
824  *              NtQueryInformationThread  (NTDLL.@)
825  *              ZwQueryInformationThread  (NTDLL.@)
826  */
827 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
828                                           void *data, ULONG length, ULONG *ret_len )
829 {
830     NTSTATUS status;
831
832     switch(class)
833     {
834     case ThreadBasicInformation:
835         {
836             THREAD_BASIC_INFORMATION info;
837
838             SERVER_START_REQ( get_thread_info )
839             {
840                 req->handle = handle;
841                 req->tid_in = 0;
842                 if (!(status = wine_server_call( req )))
843                 {
844                     info.ExitStatus             = reply->exit_code;
845                     info.TebBaseAddress         = reply->teb;
846                     info.ClientId.UniqueProcess = (HANDLE)reply->pid;
847                     info.ClientId.UniqueThread  = (HANDLE)reply->tid;
848                     info.AffinityMask           = reply->affinity;
849                     info.Priority               = reply->priority;
850                     info.BasePriority           = reply->priority;  /* FIXME */
851                 }
852             }
853             SERVER_END_REQ;
854             if (status == STATUS_SUCCESS)
855             {
856                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
857                 if (ret_len) *ret_len = min( length, sizeof(info) );
858             }
859         }
860         return status;
861     case ThreadTimes:
862         {
863             KERNEL_USER_TIMES   kusrt;
864             /* We need to do a server call to get the creation time or exit time */
865             /* This works on any thread */
866             SERVER_START_REQ( get_thread_info )
867             {
868                 req->handle = handle;
869                 req->tid_in = 0;
870                 status = wine_server_call( req );
871                 if (status == STATUS_SUCCESS)
872                 {
873                     RtlSecondsSince1970ToTime( reply->creation_time, &kusrt.CreateTime );
874                     RtlSecondsSince1970ToTime( reply->exit_time, &kusrt.ExitTime );
875                 }
876             }
877             SERVER_END_REQ;
878             if (status == STATUS_SUCCESS)
879             {
880                 /* We call times(2) for kernel time or user time */
881                 /* We can only (portably) do this for the current thread */
882                 if (handle == GetCurrentThread())
883                 {
884                     struct tms time_buf;
885                     long clocks_per_sec = sysconf(_SC_CLK_TCK);
886
887                     times(&time_buf);
888                     kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
889                     kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
890                 }
891                 else
892                 {
893                     kusrt.KernelTime.QuadPart = 0;
894                     kusrt.UserTime.QuadPart = 0;
895                     FIXME("Cannot get kerneltime or usertime of other threads\n");
896                 }
897                 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
898                 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
899             }
900         }
901         return status;
902     case ThreadPriority:
903     case ThreadBasePriority:
904     case ThreadAffinityMask:
905     case ThreadImpersonationToken:
906     case ThreadDescriptorTableEntry:
907     case ThreadEnableAlignmentFaultFixup:
908     case ThreadEventPair_Reusable:
909     case ThreadQuerySetWin32StartAddress:
910     case ThreadZeroTlsCell:
911     case ThreadPerformanceCount:
912     case ThreadAmILastThread:
913     case ThreadIdealProcessor:
914     case ThreadPriorityBoost:
915     case ThreadSetTlsArrayAddress:
916     case ThreadIsIoPending:
917     default:
918         FIXME( "info class %d not supported yet\n", class );
919         return STATUS_NOT_IMPLEMENTED;
920     }
921 }
922
923
924 /******************************************************************************
925  *              NtSetInformationThread  (NTDLL.@)
926  *              ZwSetInformationThread  (NTDLL.@)
927  */
928 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
929                                         LPCVOID data, ULONG length )
930 {
931     NTSTATUS status;
932     switch(class)
933     {
934     case ThreadZeroTlsCell:
935         if (handle == GetCurrentThread())
936         {
937             LIST_ENTRY *entry;
938             DWORD index;
939
940             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
941             index = *(const DWORD *)data;
942             if (index < TLS_MINIMUM_AVAILABLE)
943             {
944                 RtlAcquirePebLock();
945                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
946                 {
947                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
948                     teb->TlsSlots[index] = 0;
949                 }
950                 RtlReleasePebLock();
951             }
952             else
953             {
954                 index -= TLS_MINIMUM_AVAILABLE;
955                 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
956                     return STATUS_INVALID_PARAMETER;
957                 RtlAcquirePebLock();
958                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
959                 {
960                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
961                     if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
962                 }
963                 RtlReleasePebLock();
964             }
965             return STATUS_SUCCESS;
966         }
967         FIXME( "ZeroTlsCell not supported on other threads\n" );
968         return STATUS_NOT_IMPLEMENTED;
969
970     case ThreadImpersonationToken:
971         {
972             const HANDLE *phToken = data;
973             if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
974             TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
975             SERVER_START_REQ( set_thread_info )
976             {
977                 req->handle   = handle;
978                 req->token    = *phToken;
979                 req->mask     = SET_THREAD_INFO_TOKEN;
980                 status = wine_server_call( req );
981             }
982             SERVER_END_REQ;
983         }
984         return status;
985     case ThreadBasePriority:
986         {
987             const DWORD *pprio = data;
988             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
989             SERVER_START_REQ( set_thread_info )
990             {
991                 req->handle   = handle;
992                 req->priority = *pprio;
993                 req->mask     = SET_THREAD_INFO_PRIORITY;
994                 status = wine_server_call( req );
995             }
996             SERVER_END_REQ;
997         }
998         return status;
999     case ThreadAffinityMask:
1000         {
1001             const DWORD *paff = data;
1002             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1003             SERVER_START_REQ( set_thread_info )
1004             {
1005                 req->handle   = handle;
1006                 req->affinity = *paff;
1007                 req->mask     = SET_THREAD_INFO_AFFINITY;
1008                 status = wine_server_call( req );
1009             }
1010             SERVER_END_REQ;
1011         }
1012         return status;
1013     case ThreadBasicInformation:
1014     case ThreadTimes:
1015     case ThreadPriority:
1016     case ThreadDescriptorTableEntry:
1017     case ThreadEnableAlignmentFaultFixup:
1018     case ThreadEventPair_Reusable:
1019     case ThreadQuerySetWin32StartAddress:
1020     case ThreadPerformanceCount:
1021     case ThreadAmILastThread:
1022     case ThreadIdealProcessor:
1023     case ThreadPriorityBoost:
1024     case ThreadSetTlsArrayAddress:
1025     case ThreadIsIoPending:
1026     default:
1027         FIXME( "info class %d not supported yet\n", class );
1028         return STATUS_NOT_IMPLEMENTED;
1029     }
1030 }
1031
1032
1033 /**********************************************************************
1034  *           NtCurrentTeb   (NTDLL.@)
1035  */
1036 #if defined(__i386__) && defined(__GNUC__)
1037
1038 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
1039
1040 #elif defined(__i386__) && defined(_MSC_VER)
1041
1042 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1043
1044 #else
1045
1046 /**********************************************************************/
1047
1048 TEB * WINAPI NtCurrentTeb(void)
1049 {
1050     return pthread_functions.get_current_teb();
1051 }
1052
1053 #endif  /* __i386__ */