winhttp/tests: Make sure proxy settings are restored.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <stdarg.h>
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
32 #endif
33 #ifdef HAVE_SYS_SYSCALL_H
34 #include <sys/syscall.h>
35 #endif
36
37 #define NONAMELESSUNION
38 #include "ntstatus.h"
39 #define WIN32_NO_STATUS
40 #include "winternl.h"
41 #include "wine/library.h"
42 #include "wine/server.h"
43 #include "wine/debug.h"
44 #include "ntdll_misc.h"
45 #include "ddk/wdm.h"
46 #include "wine/exception.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(thread);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50
51 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
52
53 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
54
55 /* info passed to a starting thread */
56 struct startup_info
57 {
58     TEB                            *teb;
59     PRTL_THREAD_START_ROUTINE       entry_point;
60     void                           *entry_arg;
61 };
62
63 static PEB *peb;
64 static PEB_LDR_DATA ldr;
65 static RTL_USER_PROCESS_PARAMETERS params;  /* default parameters if no parent */
66 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
67 static RTL_BITMAP tls_bitmap;
68 static RTL_BITMAP tls_expansion_bitmap;
69 static RTL_BITMAP fls_bitmap;
70 static LIST_ENTRY tls_links;
71 static int nb_threads = 1;
72
73 /***********************************************************************
74  *           get_unicode_string
75  *
76  * Copy a unicode string from the startup info.
77  */
78 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
79 {
80     str->Buffer = *dst;
81     str->Length = len;
82     str->MaximumLength = len + sizeof(WCHAR);
83     memcpy( str->Buffer, *src, len );
84     str->Buffer[len / sizeof(WCHAR)] = 0;
85     *src += len / sizeof(WCHAR);
86     *dst += len / sizeof(WCHAR) + 1;
87 }
88
89 /***********************************************************************
90  *           init_user_process_params
91  *
92  * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
93  */
94 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
95 {
96     void *ptr;
97     WCHAR *src, *dst;
98     SIZE_T info_size, env_size, size, alloc_size;
99     NTSTATUS status;
100     startup_info_t *info;
101     RTL_USER_PROCESS_PARAMETERS *params = NULL;
102
103     if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
104         return STATUS_NO_MEMORY;
105
106     SERVER_START_REQ( get_startup_info )
107     {
108         wine_server_set_reply( req, info, data_size );
109         if (!(status = wine_server_call( req )))
110         {
111             data_size = wine_server_reply_size( reply );
112             info_size = reply->info_size;
113             env_size  = data_size - info_size;
114             *exe_file = wine_server_ptr_handle( reply->exe_file );
115         }
116     }
117     SERVER_END_REQ;
118     if (status != STATUS_SUCCESS) goto done;
119
120     size = sizeof(*params);
121     size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
122     size += info->dllpath_len + sizeof(WCHAR);
123     size += info->imagepath_len + sizeof(WCHAR);
124     size += info->cmdline_len + sizeof(WCHAR);
125     size += info->title_len + sizeof(WCHAR);
126     size += info->desktop_len + sizeof(WCHAR);
127     size += info->shellinfo_len + sizeof(WCHAR);
128     size += info->runtime_len + sizeof(WCHAR);
129
130     alloc_size = size;
131     status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &alloc_size,
132                                       MEM_COMMIT, PAGE_READWRITE );
133     if (status != STATUS_SUCCESS) goto done;
134
135     NtCurrentTeb()->Peb->ProcessParameters = params;
136     params->AllocationSize  = alloc_size;
137     params->Size            = size;
138     params->Flags           = PROCESS_PARAMS_FLAG_NORMALIZED;
139     params->DebugFlags      = info->debug_flags;
140     params->ConsoleHandle   = wine_server_ptr_handle( info->console );
141     params->ConsoleFlags    = info->console_flags;
142     params->hStdInput       = wine_server_ptr_handle( info->hstdin );
143     params->hStdOutput      = wine_server_ptr_handle( info->hstdout );
144     params->hStdError       = wine_server_ptr_handle( info->hstderr );
145     params->dwX             = info->x;
146     params->dwY             = info->y;
147     params->dwXSize         = info->xsize;
148     params->dwYSize         = info->ysize;
149     params->dwXCountChars   = info->xchars;
150     params->dwYCountChars   = info->ychars;
151     params->dwFillAttribute = info->attribute;
152     params->dwFlags         = info->flags;
153     params->wShowWindow     = info->show;
154
155     src = (WCHAR *)(info + 1);
156     dst = (WCHAR *)(params + 1);
157
158     /* current directory needs more space */
159     get_unicode_string( &params->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
160     params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
161     dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
162
163     get_unicode_string( &params->DllPath, &src, &dst, info->dllpath_len );
164     get_unicode_string( &params->ImagePathName, &src, &dst, info->imagepath_len );
165     get_unicode_string( &params->CommandLine, &src, &dst, info->cmdline_len );
166     get_unicode_string( &params->WindowTitle, &src, &dst, info->title_len );
167     get_unicode_string( &params->Desktop, &src, &dst, info->desktop_len );
168     get_unicode_string( &params->ShellInfo, &src, &dst, info->shellinfo_len );
169
170     /* runtime info isn't a real string */
171     params->RuntimeInfo.Buffer = dst;
172     params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
173     memcpy( dst, src, info->runtime_len );
174
175     /* environment needs to be a separate memory block */
176     ptr = NULL;
177     alloc_size = max( 1, env_size );
178     status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
179                                       MEM_COMMIT, PAGE_READWRITE );
180     if (status != STATUS_SUCCESS) goto done;
181     memcpy( ptr, (char *)info + info_size, env_size );
182     params->Environment = ptr;
183
184 done:
185     RtlFreeHeap( GetProcessHeap(), 0, info );
186     return status;
187 }
188
189 /***********************************************************************
190  *           thread_init
191  *
192  * Setup the initial thread.
193  *
194  * NOTES: The first allocated TEB on NT is at 0x7ffde000.
195  */
196 HANDLE thread_init(void)
197 {
198     TEB *teb;
199     void *addr;
200     SIZE_T size, info_size;
201     HANDLE exe_file = 0;
202     LARGE_INTEGER now;
203     NTSTATUS status;
204     struct ntdll_thread_data *thread_data;
205     static struct debug_info debug_info;  /* debug info for initial thread */
206
207     virtual_init();
208
209     /* reserve space for shared user data */
210
211     addr = (void *)0x7ffe0000;
212     size = 0x10000;
213     status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
214                                       MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
215     if (status)
216     {
217         MESSAGE( "wine: failed to map the shared user data: %08x\n", status );
218         exit(1);
219     }
220     user_shared_data = addr;
221
222     /* allocate and initialize the PEB */
223
224     addr = NULL;
225     size = sizeof(*peb);
226     NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
227                              MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
228     peb = addr;
229
230     peb->ProcessParameters  = &params;
231     peb->TlsBitmap          = &tls_bitmap;
232     peb->TlsExpansionBitmap = &tls_expansion_bitmap;
233     peb->FlsBitmap          = &fls_bitmap;
234     peb->LdrData            = &ldr;
235     params.CurrentDirectory.DosPath.Buffer = current_dir;
236     params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
237     params.wShowWindow = 1; /* SW_SHOWNORMAL */
238     ldr.Length = sizeof(ldr);
239     RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
240     RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
241                          sizeof(peb->TlsExpansionBitmapBits) * 8 );
242     RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
243     InitializeListHead( &peb->FlsListHead );
244     InitializeListHead( &ldr.InLoadOrderModuleList );
245     InitializeListHead( &ldr.InMemoryOrderModuleList );
246     InitializeListHead( &ldr.InInitializationOrderModuleList );
247     InitializeListHead( &tls_links );
248
249     /* allocate and initialize the initial TEB */
250
251     signal_alloc_thread( &teb );
252     teb->Peb = peb;
253     teb->Tib.StackBase = (void *)~0UL;
254     teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
255     teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
256
257     thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
258     thread_data->request_fd = -1;
259     thread_data->reply_fd   = -1;
260     thread_data->wait_fd[0] = -1;
261     thread_data->wait_fd[1] = -1;
262     thread_data->debug_info = &debug_info;
263     InsertHeadList( &tls_links, &teb->TlsLinks );
264
265     signal_init_thread( teb );
266     virtual_init_threading();
267
268     debug_info.str_pos = debug_info.strings;
269     debug_info.out_pos = debug_info.output;
270     debug_init();
271
272     /* setup the server connection */
273     server_init_process();
274     info_size = server_init_thread( peb );
275
276     /* create the process heap */
277     if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
278     {
279         MESSAGE( "wine: failed to create the process heap\n" );
280         exit(1);
281     }
282
283     /* allocate user parameters */
284     if (info_size)
285     {
286         init_user_process_params( info_size, &exe_file );
287     }
288     else
289     {
290         if (isatty(0) || isatty(1) || isatty(2))
291             params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
292         if (!isatty(0))
293             wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  OBJ_INHERIT, &params.hStdInput );
294         if (!isatty(1))
295             wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
296         if (!isatty(2))
297             wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
298     }
299
300     /* initialize time values in user_shared_data */
301     NtQuerySystemTime( &now );
302     user_shared_data->SystemTime.LowPart = now.u.LowPart;
303     user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
304     user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
305     user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
306     user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
307     user_shared_data->TickCountMultiplier = 1 << 24;
308
309     fill_cpu_info();
310
311     return exe_file;
312 }
313
314
315 /***********************************************************************
316  *           terminate_thread
317  */
318 void terminate_thread( int status )
319 {
320     pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
321     if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
322
323     close( ntdll_get_thread_data()->wait_fd[0] );
324     close( ntdll_get_thread_data()->wait_fd[1] );
325     close( ntdll_get_thread_data()->reply_fd );
326     close( ntdll_get_thread_data()->request_fd );
327     pthread_exit( UIntToPtr(status) );
328 }
329
330
331 /***********************************************************************
332  *           exit_thread
333  */
334 void exit_thread( int status )
335 {
336     static void *prev_teb;
337     TEB *teb;
338
339     if (status)  /* send the exit code to the server (0 is already the default) */
340     {
341         SERVER_START_REQ( terminate_thread )
342         {
343             req->handle    = wine_server_obj_handle( GetCurrentThread() );
344             req->exit_code = status;
345             wine_server_call( req );
346         }
347         SERVER_END_REQ;
348     }
349
350     if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
351     {
352         LdrShutdownProcess();
353         exit( status );
354     }
355
356     LdrShutdownThread();
357     RtlAcquirePebLock();
358     RemoveEntryList( &NtCurrentTeb()->TlsLinks );
359     RtlReleasePebLock();
360     RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
361     RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
362
363     pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
364
365     if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
366     {
367         struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
368
369         if (thread_data->pthread_id)
370         {
371             pthread_join( thread_data->pthread_id, NULL );
372             signal_free_thread( teb );
373         }
374     }
375
376     close( ntdll_get_thread_data()->wait_fd[0] );
377     close( ntdll_get_thread_data()->wait_fd[1] );
378     close( ntdll_get_thread_data()->reply_fd );
379     close( ntdll_get_thread_data()->request_fd );
380     pthread_exit( UIntToPtr(status) );
381 }
382
383
384 /***********************************************************************
385  *           start_thread
386  *
387  * Startup routine for a newly created thread.
388  */
389 static void start_thread( struct startup_info *info )
390 {
391     TEB *teb = info->teb;
392     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
393     PRTL_THREAD_START_ROUTINE func = info->entry_point;
394     void *arg = info->entry_arg;
395     struct debug_info debug_info;
396
397     debug_info.str_pos = debug_info.strings;
398     debug_info.out_pos = debug_info.output;
399     thread_data->debug_info = &debug_info;
400     thread_data->pthread_id = pthread_self();
401
402     signal_init_thread( teb );
403     server_init_thread( func );
404     pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
405
406     RtlAcquirePebLock();
407     InsertHeadList( &tls_links, &teb->TlsLinks );
408     RtlReleasePebLock();
409
410     MODULE_DllThreadAttach( NULL );
411
412     if (TRACE_ON(relay))
413         DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
414
415     call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
416 }
417
418
419 /***********************************************************************
420  *              RtlCreateUserThread   (NTDLL.@)
421  */
422 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
423                                      BOOLEAN suspended, PVOID stack_addr,
424                                      SIZE_T stack_reserve, SIZE_T stack_commit,
425                                      PRTL_THREAD_START_ROUTINE start, void *param,
426                                      HANDLE *handle_ptr, CLIENT_ID *id )
427 {
428     sigset_t sigset;
429     pthread_t pthread_id;
430     pthread_attr_t attr;
431     struct ntdll_thread_data *thread_data;
432     struct startup_info *info = NULL;
433     HANDLE handle = 0;
434     TEB *teb = NULL;
435     DWORD tid = 0;
436     int request_pipe[2];
437     NTSTATUS status;
438
439     if (process != NtCurrentProcess())
440     {
441         apc_call_t call;
442         apc_result_t result;
443
444         memset( &call, 0, sizeof(call) );
445
446         call.create_thread.type    = APC_CREATE_THREAD;
447         call.create_thread.func    = wine_server_client_ptr( start );
448         call.create_thread.arg     = wine_server_client_ptr( param );
449         call.create_thread.reserve = stack_reserve;
450         call.create_thread.commit  = stack_commit;
451         call.create_thread.suspend = suspended;
452         status = NTDLL_queue_process_apc( process, &call, &result );
453         if (status != STATUS_SUCCESS) return status;
454
455         if (result.create_thread.status == STATUS_SUCCESS)
456         {
457             if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
458             if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
459             else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
460         }
461         return result.create_thread.status;
462     }
463
464     if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
465     wine_server_send_fd( request_pipe[0] );
466
467     SERVER_START_REQ( new_thread )
468     {
469         req->access     = THREAD_ALL_ACCESS;
470         req->attributes = 0;  /* FIXME */
471         req->suspend    = suspended;
472         req->request_fd = request_pipe[0];
473         if (!(status = wine_server_call( req )))
474         {
475             handle = wine_server_ptr_handle( reply->handle );
476             tid = reply->tid;
477         }
478         close( request_pipe[0] );
479     }
480     SERVER_END_REQ;
481
482     if (status)
483     {
484         close( request_pipe[1] );
485         return status;
486     }
487
488     pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
489
490     if ((status = signal_alloc_thread( &teb ))) goto error;
491
492     teb->Peb = NtCurrentTeb()->Peb;
493     teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
494     teb->ClientId.UniqueThread  = ULongToHandle(tid);
495     teb->StaticUnicodeString.Buffer        = teb->StaticUnicodeBuffer;
496     teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
497
498     info = (struct startup_info *)(teb + 1);
499     info->teb         = teb;
500     info->entry_point = start;
501     info->entry_arg   = param;
502
503     thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
504     thread_data->request_fd  = request_pipe[1];
505     thread_data->reply_fd    = -1;
506     thread_data->wait_fd[0]  = -1;
507     thread_data->wait_fd[1]  = -1;
508
509     if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
510
511     pthread_attr_init( &attr );
512     pthread_attr_setstack( &attr, teb->DeallocationStack,
513                            (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
514     pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
515     interlocked_xchg_add( &nb_threads, 1 );
516     if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
517     {
518         interlocked_xchg_add( &nb_threads, -1 );
519         pthread_attr_destroy( &attr );
520         status = STATUS_NO_MEMORY;
521         goto error;
522     }
523     pthread_attr_destroy( &attr );
524     pthread_sigmask( SIG_SETMASK, &sigset, NULL );
525
526     if (id) id->UniqueThread = ULongToHandle(tid);
527     if (handle_ptr) *handle_ptr = handle;
528     else NtClose( handle );
529
530     return STATUS_SUCCESS;
531
532 error:
533     if (teb) signal_free_thread( teb );
534     if (handle) NtClose( handle );
535     pthread_sigmask( SIG_SETMASK, &sigset, NULL );
536     close( request_pipe[1] );
537     return status;
538 }
539
540
541 /******************************************************************************
542  *              RtlGetNtGlobalFlags   (NTDLL.@)
543  */
544 ULONG WINAPI RtlGetNtGlobalFlags(void)
545 {
546     if (!peb) return 0;  /* init not done yet */
547     return peb->NtGlobalFlag;
548 }
549
550
551 /***********************************************************************
552  *              NtOpenThread   (NTDLL.@)
553  *              ZwOpenThread   (NTDLL.@)
554  */
555 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
556                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
557 {
558     NTSTATUS ret;
559
560     SERVER_START_REQ( open_thread )
561     {
562         req->tid        = HandleToULong(id->UniqueThread);
563         req->access     = access;
564         req->attributes = attr ? attr->Attributes : 0;
565         ret = wine_server_call( req );
566         *handle = wine_server_ptr_handle( reply->handle );
567     }
568     SERVER_END_REQ;
569     return ret;
570 }
571
572
573 /******************************************************************************
574  *              NtSuspendThread   (NTDLL.@)
575  *              ZwSuspendThread   (NTDLL.@)
576  */
577 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
578 {
579     NTSTATUS ret;
580
581     SERVER_START_REQ( suspend_thread )
582     {
583         req->handle = wine_server_obj_handle( handle );
584         if (!(ret = wine_server_call( req ))) *count = reply->count;
585     }
586     SERVER_END_REQ;
587     return ret;
588 }
589
590
591 /******************************************************************************
592  *              NtResumeThread   (NTDLL.@)
593  *              ZwResumeThread   (NTDLL.@)
594  */
595 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
596 {
597     NTSTATUS ret;
598
599     SERVER_START_REQ( resume_thread )
600     {
601         req->handle = wine_server_obj_handle( handle );
602         if (!(ret = wine_server_call( req ))) *count = reply->count;
603     }
604     SERVER_END_REQ;
605     return ret;
606 }
607
608
609 /******************************************************************************
610  *              NtAlertResumeThread   (NTDLL.@)
611  *              ZwAlertResumeThread   (NTDLL.@)
612  */
613 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
614 {
615     FIXME( "stub: should alert thread %p\n", handle );
616     return NtResumeThread( handle, count );
617 }
618
619
620 /******************************************************************************
621  *              NtAlertThread   (NTDLL.@)
622  *              ZwAlertThread   (NTDLL.@)
623  */
624 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
625 {
626     FIXME( "stub: %p\n", handle );
627     return STATUS_NOT_IMPLEMENTED;
628 }
629
630
631 /******************************************************************************
632  *              NtTerminateThread  (NTDLL.@)
633  *              ZwTerminateThread  (NTDLL.@)
634  */
635 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
636 {
637     NTSTATUS ret;
638     BOOL self;
639
640     SERVER_START_REQ( terminate_thread )
641     {
642         req->handle    = wine_server_obj_handle( handle );
643         req->exit_code = exit_code;
644         ret = wine_server_call( req );
645         self = !ret && reply->self;
646     }
647     SERVER_END_REQ;
648
649     if (self) abort_thread( exit_code );
650     return ret;
651 }
652
653
654 /******************************************************************************
655  *              NtQueueApcThread  (NTDLL.@)
656  */
657 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
658                                   ULONG_PTR arg2, ULONG_PTR arg3 )
659 {
660     NTSTATUS ret;
661     SERVER_START_REQ( queue_apc )
662     {
663         req->handle = wine_server_obj_handle( handle );
664         if (func)
665         {
666             req->call.type         = APC_USER;
667             req->call.user.func    = wine_server_client_ptr( func );
668             req->call.user.args[0] = arg1;
669             req->call.user.args[1] = arg2;
670             req->call.user.args[2] = arg3;
671         }
672         else req->call.type = APC_NONE;  /* wake up only */
673         ret = wine_server_call( req );
674     }
675     SERVER_END_REQ;
676     return ret;
677 }
678
679
680 /***********************************************************************
681  *              NtSetContextThread  (NTDLL.@)
682  *              ZwSetContextThread  (NTDLL.@)
683  */
684 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
685 {
686     NTSTATUS ret;
687     DWORD dummy, i;
688     BOOL self = FALSE;
689
690 #ifdef __i386__
691     /* on i386 debug registers always require a server call */
692     self = (handle == GetCurrentThread());
693     if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
694     {
695         self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
696                 ntdll_get_thread_data()->dr1 == context->Dr1 &&
697                 ntdll_get_thread_data()->dr2 == context->Dr2 &&
698                 ntdll_get_thread_data()->dr3 == context->Dr3 &&
699                 ntdll_get_thread_data()->dr6 == context->Dr6 &&
700                 ntdll_get_thread_data()->dr7 == context->Dr7);
701     }
702 #endif
703
704     if (!self)
705     {
706         context_t server_context;
707
708         context_to_server( &server_context, context );
709
710         SERVER_START_REQ( set_thread_context )
711         {
712             req->handle  = wine_server_obj_handle( handle );
713             req->suspend = 1;
714             wine_server_add_data( req, &server_context, sizeof(server_context) );
715             ret = wine_server_call( req );
716             self = reply->self;
717         }
718         SERVER_END_REQ;
719
720         if (ret == STATUS_PENDING)
721         {
722             for (i = 0; i < 100; i++)
723             {
724                 SERVER_START_REQ( set_thread_context )
725                 {
726                     req->handle  = wine_server_obj_handle( handle );
727                     req->suspend = 0;
728                     wine_server_add_data( req, &server_context, sizeof(server_context) );
729                     ret = wine_server_call( req );
730                 }
731                 SERVER_END_REQ;
732                 if (ret == STATUS_PENDING)
733                 {
734                     LARGE_INTEGER timeout;
735                     timeout.QuadPart = -10000;
736                     NtDelayExecution( FALSE, &timeout );
737                 }
738                 else break;
739             }
740             NtResumeThread( handle, &dummy );
741             if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
742         }
743
744         if (ret) return ret;
745     }
746
747     if (self) set_cpu_context( context );
748     return STATUS_SUCCESS;
749 }
750
751
752 /* convert CPU-specific flags to generic server flags */
753 static inline unsigned int get_server_context_flags( DWORD flags )
754 {
755     unsigned int ret = 0;
756
757     flags &= 0x3f;  /* mask CPU id flags */
758     if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
759     if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
760 #ifdef CONTEXT_SEGMENTS
761     if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
762 #endif
763 #ifdef CONTEXT_FLOATING_POINT
764     if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
765 #endif
766 #ifdef CONTEXT_DEBUG_REGISTERS
767     if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
768 #endif
769 #ifdef CONTEXT_EXTENDED_REGISTERS
770     if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
771 #endif
772     return ret;
773 }
774
775 /***********************************************************************
776  *              NtGetContextThread  (NTDLL.@)
777  *              ZwGetContextThread  (NTDLL.@)
778  */
779 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
780 {
781     NTSTATUS ret;
782     DWORD dummy, i;
783     DWORD needed_flags = context->ContextFlags;
784     BOOL self = (handle == GetCurrentThread());
785
786 #ifdef __i386__
787     /* on i386 debug registers always require a server call */
788     if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
789 #endif
790
791     if (!self)
792     {
793         unsigned int server_flags = get_server_context_flags( context->ContextFlags );
794         context_t server_context;
795
796         SERVER_START_REQ( get_thread_context )
797         {
798             req->handle  = wine_server_obj_handle( handle );
799             req->flags   = server_flags;
800             req->suspend = 1;
801             wine_server_set_reply( req, &server_context, sizeof(server_context) );
802             ret = wine_server_call( req );
803             self = reply->self;
804         }
805         SERVER_END_REQ;
806
807         if (ret == STATUS_PENDING)
808         {
809             for (i = 0; i < 100; i++)
810             {
811                 SERVER_START_REQ( get_thread_context )
812                 {
813                     req->handle  = wine_server_obj_handle( handle );
814                     req->flags   = server_flags;
815                     req->suspend = 0;
816                     wine_server_set_reply( req, &server_context, sizeof(server_context) );
817                     ret = wine_server_call( req );
818                 }
819                 SERVER_END_REQ;
820                 if (ret == STATUS_PENDING)
821                 {
822                     LARGE_INTEGER timeout;
823                     timeout.QuadPart = -10000;
824                     NtDelayExecution( FALSE, &timeout );
825                 }
826                 else break;
827             }
828             NtResumeThread( handle, &dummy );
829             if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
830         }
831         if (!ret) ret = context_from_server( context, &server_context );
832         if (ret) return ret;
833         needed_flags &= ~context->ContextFlags;
834     }
835
836     if (self)
837     {
838         if (needed_flags)
839         {
840             CONTEXT ctx;
841             RtlCaptureContext( &ctx );
842             copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
843             context->ContextFlags |= ctx.ContextFlags & needed_flags;
844         }
845 #ifdef __i386__
846         /* update the cached version of the debug registers */
847         if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
848         {
849             ntdll_get_thread_data()->dr0 = context->Dr0;
850             ntdll_get_thread_data()->dr1 = context->Dr1;
851             ntdll_get_thread_data()->dr2 = context->Dr2;
852             ntdll_get_thread_data()->dr3 = context->Dr3;
853             ntdll_get_thread_data()->dr6 = context->Dr6;
854             ntdll_get_thread_data()->dr7 = context->Dr7;
855         }
856 #endif
857     }
858     return STATUS_SUCCESS;
859 }
860
861
862 /******************************************************************************
863  *              NtQueryInformationThread  (NTDLL.@)
864  *              ZwQueryInformationThread  (NTDLL.@)
865  */
866 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
867                                           void *data, ULONG length, ULONG *ret_len )
868 {
869     NTSTATUS status;
870
871     switch(class)
872     {
873     case ThreadBasicInformation:
874         {
875             THREAD_BASIC_INFORMATION info;
876             const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
877
878             SERVER_START_REQ( get_thread_info )
879             {
880                 req->handle = wine_server_obj_handle( handle );
881                 req->tid_in = 0;
882                 if (!(status = wine_server_call( req )))
883                 {
884                     info.ExitStatus             = reply->exit_code;
885                     info.TebBaseAddress         = wine_server_get_ptr( reply->teb );
886                     info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
887                     info.ClientId.UniqueThread  = ULongToHandle(reply->tid);
888                     info.AffinityMask           = reply->affinity & affinity_mask;
889                     info.Priority               = reply->priority;
890                     info.BasePriority           = reply->priority;  /* FIXME */
891                 }
892             }
893             SERVER_END_REQ;
894             if (status == STATUS_SUCCESS)
895             {
896                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
897                 if (ret_len) *ret_len = min( length, sizeof(info) );
898             }
899         }
900         return status;
901     case ThreadAffinityMask:
902         {
903             const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
904             ULONG_PTR affinity = 0;
905
906             SERVER_START_REQ( get_thread_info )
907             {
908                 req->handle = wine_server_obj_handle( handle );
909                 req->tid_in = 0;
910                 if (!(status = wine_server_call( req )))
911                     affinity = reply->affinity & affinity_mask;
912             }
913             SERVER_END_REQ;
914             if (status == STATUS_SUCCESS)
915             {
916                 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
917                 if (ret_len) *ret_len = min( length, sizeof(affinity) );
918             }
919         }
920         return status;
921     case ThreadTimes:
922         {
923             KERNEL_USER_TIMES   kusrt;
924             /* We need to do a server call to get the creation time or exit time */
925             /* This works on any thread */
926             SERVER_START_REQ( get_thread_info )
927             {
928                 req->handle = wine_server_obj_handle( handle );
929                 req->tid_in = 0;
930                 status = wine_server_call( req );
931                 if (status == STATUS_SUCCESS)
932                 {
933                     kusrt.CreateTime.QuadPart = reply->creation_time;
934                     kusrt.ExitTime.QuadPart = reply->exit_time;
935                 }
936             }
937             SERVER_END_REQ;
938             if (status == STATUS_SUCCESS)
939             {
940                 /* We call times(2) for kernel time or user time */
941                 /* We can only (portably) do this for the current thread */
942                 if (handle == GetCurrentThread())
943                 {
944                     struct tms time_buf;
945                     long clocks_per_sec = sysconf(_SC_CLK_TCK);
946
947                     times(&time_buf);
948                     kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
949                     kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
950                 }
951                 else
952                 {
953                     static BOOL reported = FALSE;
954
955                     kusrt.KernelTime.QuadPart = 0;
956                     kusrt.UserTime.QuadPart = 0;
957                     if (reported)
958                         TRACE("Cannot get kerneltime or usertime of other threads\n");
959                     else
960                     {
961                         FIXME("Cannot get kerneltime or usertime of other threads\n");
962                         reported = TRUE;
963                     }
964                 }
965                 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
966                 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
967             }
968         }
969         return status;
970     case ThreadDescriptorTableEntry:
971         {
972 #ifdef __i386__
973             THREAD_DESCRIPTOR_INFORMATION*      tdi = data;
974             if (length < sizeof(*tdi))
975                 status = STATUS_INFO_LENGTH_MISMATCH;
976             else if (!(tdi->Selector & 4))  /* GDT selector */
977             {
978                 unsigned sel = tdi->Selector & ~3;  /* ignore RPL */
979                 status = STATUS_SUCCESS;
980                 if (!sel)  /* null selector */
981                     memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
982                 else
983                 {
984                     tdi->Entry.BaseLow                   = 0;
985                     tdi->Entry.HighWord.Bits.BaseMid     = 0;
986                     tdi->Entry.HighWord.Bits.BaseHi      = 0;
987                     tdi->Entry.LimitLow                  = 0xffff;
988                     tdi->Entry.HighWord.Bits.LimitHi     = 0xf;
989                     tdi->Entry.HighWord.Bits.Dpl         = 3;
990                     tdi->Entry.HighWord.Bits.Sys         = 0;
991                     tdi->Entry.HighWord.Bits.Pres        = 1;
992                     tdi->Entry.HighWord.Bits.Granularity = 1;
993                     tdi->Entry.HighWord.Bits.Default_Big = 1;
994                     tdi->Entry.HighWord.Bits.Type        = 0x12;
995                     /* it has to be one of the system GDT selectors */
996                     if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
997                     {
998                         if (sel == (wine_get_cs() & ~3))
999                             tdi->Entry.HighWord.Bits.Type |= 8;  /* code segment */
1000                         else status = STATUS_ACCESS_DENIED;
1001                     }
1002                 }
1003             }
1004             else
1005             {
1006                 SERVER_START_REQ( get_selector_entry )
1007                 {
1008                     req->handle = wine_server_obj_handle( handle );
1009                     req->entry = tdi->Selector >> 3;
1010                     status = wine_server_call( req );
1011                     if (!status)
1012                     {
1013                         if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1014                             status = STATUS_ACCESS_VIOLATION;
1015                         else
1016                         {
1017                             wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1018                             wine_ldt_set_limit( &tdi->Entry, reply->limit );
1019                             wine_ldt_set_flags( &tdi->Entry, reply->flags );
1020                         }
1021                     }
1022                 }
1023                 SERVER_END_REQ;
1024             }
1025             if (status == STATUS_SUCCESS && ret_len)
1026                 /* yes, that's a bit strange, but it's the way it is */
1027                 *ret_len = sizeof(LDT_ENTRY);
1028 #else
1029             status = STATUS_NOT_IMPLEMENTED;
1030 #endif
1031             return status;
1032         }
1033     case ThreadAmILastThread:
1034         {
1035             SERVER_START_REQ(get_thread_info)
1036             {
1037                 req->handle = wine_server_obj_handle( handle );
1038                 req->tid_in = 0;
1039                 status = wine_server_call( req );
1040                 if (status == STATUS_SUCCESS)
1041                 {
1042                     BOOLEAN last = reply->last;
1043                     if (data) memcpy( data, &last, min( length, sizeof(last) ));
1044                     if (ret_len) *ret_len = min( length, sizeof(last) );
1045                 }
1046             }
1047             SERVER_END_REQ;
1048             return status;
1049         }
1050     case ThreadPriority:
1051     case ThreadBasePriority:
1052     case ThreadImpersonationToken:
1053     case ThreadEnableAlignmentFaultFixup:
1054     case ThreadEventPair_Reusable:
1055     case ThreadQuerySetWin32StartAddress:
1056     case ThreadZeroTlsCell:
1057     case ThreadPerformanceCount:
1058     case ThreadIdealProcessor:
1059     case ThreadPriorityBoost:
1060     case ThreadSetTlsArrayAddress:
1061     case ThreadIsIoPending:
1062     default:
1063         FIXME( "info class %d not supported yet\n", class );
1064         return STATUS_NOT_IMPLEMENTED;
1065     }
1066 }
1067
1068
1069 /******************************************************************************
1070  *              NtSetInformationThread  (NTDLL.@)
1071  *              ZwSetInformationThread  (NTDLL.@)
1072  */
1073 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1074                                         LPCVOID data, ULONG length )
1075 {
1076     NTSTATUS status;
1077     switch(class)
1078     {
1079     case ThreadZeroTlsCell:
1080         if (handle == GetCurrentThread())
1081         {
1082             LIST_ENTRY *entry;
1083             DWORD index;
1084
1085             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1086             index = *(const DWORD *)data;
1087             if (index < TLS_MINIMUM_AVAILABLE)
1088             {
1089                 RtlAcquirePebLock();
1090                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1091                 {
1092                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1093                     teb->TlsSlots[index] = 0;
1094                 }
1095                 RtlReleasePebLock();
1096             }
1097             else
1098             {
1099                 index -= TLS_MINIMUM_AVAILABLE;
1100                 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1101                     return STATUS_INVALID_PARAMETER;
1102                 RtlAcquirePebLock();
1103                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1104                 {
1105                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1106                     if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1107                 }
1108                 RtlReleasePebLock();
1109             }
1110             return STATUS_SUCCESS;
1111         }
1112         FIXME( "ZeroTlsCell not supported on other threads\n" );
1113         return STATUS_NOT_IMPLEMENTED;
1114
1115     case ThreadImpersonationToken:
1116         {
1117             const HANDLE *phToken = data;
1118             if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1119             TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1120             SERVER_START_REQ( set_thread_info )
1121             {
1122                 req->handle   = wine_server_obj_handle( handle );
1123                 req->token    = wine_server_obj_handle( *phToken );
1124                 req->mask     = SET_THREAD_INFO_TOKEN;
1125                 status = wine_server_call( req );
1126             }
1127             SERVER_END_REQ;
1128         }
1129         return status;
1130     case ThreadBasePriority:
1131         {
1132             const DWORD *pprio = data;
1133             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1134             SERVER_START_REQ( set_thread_info )
1135             {
1136                 req->handle   = wine_server_obj_handle( handle );
1137                 req->priority = *pprio;
1138                 req->mask     = SET_THREAD_INFO_PRIORITY;
1139                 status = wine_server_call( req );
1140             }
1141             SERVER_END_REQ;
1142         }
1143         return status;
1144     case ThreadAffinityMask:
1145         {
1146             const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1147             ULONG_PTR req_aff;
1148
1149             if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1150             req_aff = *(const ULONG_PTR *)data;
1151             if ((ULONG)req_aff == ~0u) req_aff = affinity_mask;
1152             else if (req_aff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1153             else if (!req_aff) return STATUS_INVALID_PARAMETER;
1154             SERVER_START_REQ( set_thread_info )
1155             {
1156                 req->handle   = wine_server_obj_handle( handle );
1157                 req->affinity = req_aff;
1158                 req->mask     = SET_THREAD_INFO_AFFINITY;
1159                 status = wine_server_call( req );
1160             }
1161             SERVER_END_REQ;
1162         }
1163         return status;
1164     case ThreadHideFromDebugger:
1165         /* pretend the call succeeded to satisfy some code protectors */
1166         return STATUS_SUCCESS;
1167
1168     case ThreadBasicInformation:
1169     case ThreadTimes:
1170     case ThreadPriority:
1171     case ThreadDescriptorTableEntry:
1172     case ThreadEnableAlignmentFaultFixup:
1173     case ThreadEventPair_Reusable:
1174     case ThreadQuerySetWin32StartAddress:
1175     case ThreadPerformanceCount:
1176     case ThreadAmILastThread:
1177     case ThreadIdealProcessor:
1178     case ThreadPriorityBoost:
1179     case ThreadSetTlsArrayAddress:
1180     case ThreadIsIoPending:
1181     default:
1182         FIXME( "info class %d not supported yet\n", class );
1183         return STATUS_NOT_IMPLEMENTED;
1184     }
1185 }
1186
1187 /******************************************************************************
1188  * NtGetCurrentProcessorNumber (NTDLL.@)
1189  *
1190  * Return the processor, on which the thread is running
1191  *
1192  */
1193 ULONG WINAPI NtGetCurrentProcessorNumber(void)
1194 {
1195     ULONG processor;
1196
1197 #if defined(__linux__) && defined(__NR_getcpu)
1198     int res = syscall(__NR_getcpu, &processor, NULL, NULL);
1199     if (res != -1) return processor;
1200 #endif
1201
1202     if (NtCurrentTeb()->Peb->NumberOfProcessors > 1)
1203     {
1204         ULONG_PTR thread_mask, processor_mask;
1205         NTSTATUS status;
1206
1207         status = NtQueryInformationThread(GetCurrentThread(), ThreadAffinityMask,
1208                                           &thread_mask, sizeof(thread_mask), NULL);
1209         if (status == STATUS_SUCCESS)
1210         {
1211             for (processor = 0; processor < NtCurrentTeb()->Peb->NumberOfProcessors; processor++)
1212             {
1213                 processor_mask = (1 << processor);
1214                 if (thread_mask & processor_mask)
1215                 {
1216                     if (thread_mask != processor_mask)
1217                         FIXME("need multicore support (%d processors)\n",
1218                               NtCurrentTeb()->Peb->NumberOfProcessors);
1219                     return processor;
1220                 }
1221             }
1222         }
1223     }
1224
1225     /* fallback to the first processor */
1226     return 0;
1227 }