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