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