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