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