Enhance uxtheme to store the themed system metrics in the registry and
[wine] / dlls / ntdll / thread.c
1 /*
2  * NT threads support
3  *
4  * Copyright 1996, 2003 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <sys/types.h>
25 #ifdef HAVE_SYS_MMAN_H
26 #include <sys/mman.h>
27 #endif
28
29 #include "ntstatus.h"
30 #include "thread.h"
31 #include "winternl.h"
32 #include "wine/library.h"
33 #include "wine/server.h"
34 #include "wine/pthread.h"
35 #include "wine/debug.h"
36 #include "ntdll_misc.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(thread);
39
40 /* info passed to a starting thread */
41 struct startup_info
42 {
43     struct wine_pthread_thread_info pthread_info;
44     PRTL_THREAD_START_ROUTINE       entry_point;
45     void                           *entry_arg;
46 };
47
48 static PEB peb;
49 static PEB_LDR_DATA ldr;
50 static RTL_USER_PROCESS_PARAMETERS params;  /* default parameters if no parent */
51 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
52 static RTL_BITMAP tls_bitmap;
53 static RTL_BITMAP tls_expansion_bitmap;
54 static LIST_ENTRY tls_links;
55
56
57 /***********************************************************************
58  *           init_teb
59  */
60 static inline NTSTATUS init_teb( TEB *teb )
61 {
62     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
63
64     teb->Tib.ExceptionList = (void *)~0UL;
65     teb->Tib.StackBase     = (void *)~0UL;
66     teb->Tib.Self          = &teb->Tib;
67     teb->Peb               = &peb;
68     teb->StaticUnicodeString.Buffer        = teb->StaticUnicodeBuffer;
69     teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
70
71     if (!(thread_data->teb_sel = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
72     thread_data->request_fd = -1;
73     thread_data->reply_fd   = -1;
74     thread_data->wait_fd[0] = -1;
75     thread_data->wait_fd[1] = -1;
76
77     return STATUS_SUCCESS;
78 }
79
80
81 /***********************************************************************
82  *           free_teb
83  */
84 static inline void free_teb( TEB *teb )
85 {
86     ULONG size = 0;
87     void *addr = teb;
88     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
89
90     NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
91     wine_ldt_free_fs( thread_data->teb_sel );
92     munmap( teb, SIGNAL_STACK_SIZE + sizeof(TEB) );
93 }
94
95
96 /***********************************************************************
97  *           thread_init
98  *
99  * Setup the initial thread.
100  *
101  * NOTES: The first allocated TEB on NT is at 0x7ffde000.
102  */
103 void thread_init(void)
104 {
105     TEB *teb;
106     void *addr;
107     ULONG info_size;
108     struct ntdll_thread_data *thread_data;
109     struct wine_pthread_thread_info thread_info;
110     static struct debug_info debug_info;  /* debug info for initial thread */
111
112     peb.NumberOfProcessors = 1;
113     peb.ProcessParameters  = &params;
114     peb.TlsBitmap          = &tls_bitmap;
115     peb.TlsExpansionBitmap = &tls_expansion_bitmap;
116     peb.LdrData            = &ldr;
117     params.CurrentDirectory.DosPath.Buffer = current_dir;
118     params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
119     RtlInitializeBitMap( &tls_bitmap, peb.TlsBitmapBits, sizeof(peb.TlsBitmapBits) * 8 );
120     RtlInitializeBitMap( &tls_expansion_bitmap, peb.TlsExpansionBitmapBits,
121                          sizeof(peb.TlsExpansionBitmapBits) * 8 );
122     InitializeListHead( &ldr.InLoadOrderModuleList );
123     InitializeListHead( &ldr.InMemoryOrderModuleList );
124     InitializeListHead( &ldr.InInitializationOrderModuleList );
125     InitializeListHead( &tls_links );
126
127     thread_info.teb_size = SIGNAL_STACK_SIZE + sizeof(TEB);
128     VIRTUAL_alloc_teb( &addr, thread_info.teb_size, TRUE );
129     teb = addr;
130     init_teb( teb );
131     thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
132     thread_data->debug_info = &debug_info;
133     InsertHeadList( &tls_links, &teb->TlsLinks );
134
135     thread_info.stack_base = NULL;
136     thread_info.stack_size = 0;
137     thread_info.teb_base   = teb;
138     thread_info.teb_sel    = thread_data->teb_sel;
139     wine_pthread_init_current_teb( &thread_info );
140     wine_pthread_init_thread( &thread_info );
141
142     debug_info.str_pos = debug_info.strings;
143     debug_info.out_pos = debug_info.output;
144     debug_init();
145
146     /* setup the server connection */
147     server_init_process();
148     info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
149
150     /* create the process heap */
151     if (!(peb.ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
152     {
153         MESSAGE( "wine: failed to create the process heap\n" );
154         exit(1);
155     }
156
157     /* allocate user parameters */
158     if (info_size)
159     {
160         RTL_USER_PROCESS_PARAMETERS *params = NULL;
161
162         if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &info_size,
163                                      MEM_COMMIT, PAGE_READWRITE ) == STATUS_SUCCESS)
164         {
165             params->AllocationSize = info_size;
166             NtCurrentTeb()->Peb->ProcessParameters = params;
167         }
168     }
169     else
170     {
171         /* This is wine specific: we have no parent (we're started from unix)
172          * so, create a simple console with bare handles to unix stdio
173          */
174         wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  TRUE, &params.hStdInput );
175         wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params.hStdOutput );
176         wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params.hStdError );
177     }
178 }
179
180
181 /***********************************************************************
182  *           start_thread
183  *
184  * Startup routine for a newly created thread.
185  */
186 static void start_thread( struct wine_pthread_thread_info *info )
187 {
188     TEB *teb = info->teb_base;
189     struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
190     struct startup_info *startup_info = (struct startup_info *)info;
191     PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
192     void *arg = startup_info->entry_arg;
193     struct debug_info debug_info;
194     ULONG size;
195
196     debug_info.str_pos = debug_info.strings;
197     debug_info.out_pos = debug_info.output;
198     thread_data->debug_info = &debug_info;
199
200     wine_pthread_init_current_teb( info );
201     SIGNAL_Init();
202     server_init_thread( info->pid, info->tid, func );
203     wine_pthread_init_thread( info );
204
205     /* allocate a memory view for the stack */
206     size = info->stack_size;
207     teb->DeallocationStack = info->stack_base;
208     NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
209                              &size, MEM_SYSTEM, PAGE_READWRITE );
210     /* limit is lower than base since the stack grows down */
211     teb->Tib.StackBase  = (char *)info->stack_base + info->stack_size;
212     teb->Tib.StackLimit = info->stack_base;
213
214     /* setup the guard page */
215     size = 1;
216     NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size,
217                             PAGE_READWRITE | PAGE_GUARD, NULL );
218     RtlFreeHeap( GetProcessHeap(), 0, info );
219
220     RtlAcquirePebLock();
221     InsertHeadList( &tls_links, &teb->TlsLinks );
222     RtlReleasePebLock();
223
224     func( arg );
225 }
226
227
228 /***********************************************************************
229  *              RtlCreateUserThread   (NTDLL.@)
230  */
231 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
232                                      BOOLEAN suspended, PVOID stack_addr,
233                                      SIZE_T stack_reserve, SIZE_T stack_commit,
234                                      PRTL_THREAD_START_ROUTINE start, void *param,
235                                      HANDLE *handle_ptr, CLIENT_ID *id )
236 {
237     struct ntdll_thread_data *thread_data = NULL;
238     struct startup_info *info = NULL;
239     void *addr;
240     HANDLE handle = 0;
241     TEB *teb;
242     DWORD tid = 0;
243     int request_pipe[2];
244     NTSTATUS status;
245
246     if( ! is_current_process( process ) )
247     {
248         ERR("Unsupported on other process\n");
249         return STATUS_ACCESS_DENIED;
250     }
251
252     if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
253     fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
254     wine_server_send_fd( request_pipe[0] );
255
256     SERVER_START_REQ( new_thread )
257     {
258         req->suspend    = suspended;
259         req->inherit    = 0;  /* FIXME */
260         req->request_fd = request_pipe[0];
261         if (!(status = wine_server_call( req )))
262         {
263             handle = reply->handle;
264             tid = reply->tid;
265         }
266         close( request_pipe[0] );
267     }
268     SERVER_END_REQ;
269
270     if (status) goto error;
271
272     if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
273     {
274         status = STATUS_NO_MEMORY;
275         goto error;
276     }
277
278     info->pthread_info.teb_size = SIGNAL_STACK_SIZE + sizeof(TEB);
279     if ((status = VIRTUAL_alloc_teb( &addr, info->pthread_info.teb_size, FALSE ))) goto error;
280     teb = addr;
281     if ((status = init_teb( teb ))) goto error;
282
283     teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
284     teb->ClientId.UniqueThread  = (HANDLE)tid;
285
286     thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
287     thread_data->request_fd  = request_pipe[1];
288
289     info->pthread_info.teb_base = teb;
290     info->pthread_info.teb_sel  = thread_data->teb_sel;
291
292     if (!stack_reserve || !stack_commit)
293     {
294         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
295         if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
296         if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
297     }
298     if (stack_reserve < stack_commit) stack_reserve = stack_commit;
299     stack_reserve = (stack_reserve + 0xffff) & ~0xffff;  /* round to 64K boundary */
300     if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024;  /* Xlib needs a large stack */
301
302     info->pthread_info.stack_base = NULL;
303     info->pthread_info.stack_size = stack_reserve;
304     info->pthread_info.entry      = start_thread;
305     info->entry_point             = start;
306     info->entry_arg               = param;
307
308     if (wine_pthread_create_thread( &info->pthread_info ) == -1)
309     {
310         status = STATUS_NO_MEMORY;
311         goto error;
312     }
313
314     if (id) id->UniqueThread = (HANDLE)tid;
315     if (handle_ptr) *handle_ptr = handle;
316     else NtClose( handle );
317
318     return STATUS_SUCCESS;
319
320 error:
321     if (thread_data) wine_ldt_free_fs( thread_data->teb_sel );
322     if (addr)
323     {
324         ULONG size = 0;
325         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
326     }
327     if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
328     if (handle) NtClose( handle );
329     close( request_pipe[1] );
330     return status;
331 }
332
333
334 /***********************************************************************
335  *           RtlExitUserThread  (NTDLL.@)
336  */
337 void WINAPI RtlExitUserThread( ULONG status )
338 {
339     LdrShutdownThread();
340     server_exit_thread( status );
341 }
342
343
344 /***********************************************************************
345  *              NtOpenThread   (NTDLL.@)
346  *              ZwOpenThread   (NTDLL.@)
347  */
348 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
349                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
350 {
351     NTSTATUS ret;
352
353     SERVER_START_REQ( open_thread )
354     {
355         req->tid     = (thread_id_t)id->UniqueThread;
356         req->access  = access;
357         req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
358         ret = wine_server_call( req );
359         *handle = reply->handle;
360     }
361     SERVER_END_REQ;
362     return ret;
363 }
364
365
366 /******************************************************************************
367  *              NtSuspendThread   (NTDLL.@)
368  *              ZwSuspendThread   (NTDLL.@)
369  */
370 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
371 {
372     NTSTATUS ret;
373
374     SERVER_START_REQ( suspend_thread )
375     {
376         req->handle = handle;
377         if (!(ret = wine_server_call( req ))) *count = reply->count;
378     }
379     SERVER_END_REQ;
380     return ret;
381 }
382
383
384 /******************************************************************************
385  *              NtResumeThread   (NTDLL.@)
386  *              ZwResumeThread   (NTDLL.@)
387  */
388 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
389 {
390     NTSTATUS ret;
391
392     SERVER_START_REQ( resume_thread )
393     {
394         req->handle = handle;
395         if (!(ret = wine_server_call( req ))) *count = reply->count;
396     }
397     SERVER_END_REQ;
398     return ret;
399 }
400
401
402 /******************************************************************************
403  *              NtTerminateThread  (NTDLL.@)
404  *              ZwTerminateThread  (NTDLL.@)
405  */
406 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
407 {
408     NTSTATUS ret;
409     BOOL self, last;
410
411     SERVER_START_REQ( terminate_thread )
412     {
413         req->handle    = handle;
414         req->exit_code = exit_code;
415         ret = wine_server_call( req );
416         self = !ret && reply->self;
417         last = reply->last;
418     }
419     SERVER_END_REQ;
420
421     if (self)
422     {
423         if (last) exit( exit_code );
424         else server_abort_thread( exit_code );
425     }
426     return ret;
427 }
428
429
430 /******************************************************************************
431  *              NtQueueApcThread  (NTDLL.@)
432  */
433 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
434                                   ULONG_PTR arg2, ULONG_PTR arg3 )
435 {
436     NTSTATUS ret;
437     SERVER_START_REQ( queue_apc )
438     {
439         req->handle = handle;
440         req->user   = 1;
441         req->func   = func;
442         req->arg1   = (void *)arg1;
443         req->arg2   = (void *)arg2;
444         req->arg3   = (void *)arg3;
445         ret = wine_server_call( req );
446     }
447     SERVER_END_REQ;
448     return ret;
449 }
450
451
452 /***********************************************************************
453  *              NtSetContextThread  (NTDLL.@)
454  *              ZwSetContextThread  (NTDLL.@)
455  */
456 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
457 {
458     NTSTATUS ret;
459
460     SERVER_START_REQ( set_thread_context )
461     {
462         req->handle = handle;
463         req->flags  = context->ContextFlags;
464         wine_server_add_data( req, context, sizeof(*context) );
465         ret = wine_server_call( req );
466     }
467     SERVER_END_REQ;
468     return ret;
469 }
470
471
472 /***********************************************************************
473  *              NtGetContextThread  (NTDLL.@)
474  *              ZwGetContextThread  (NTDLL.@)
475  */
476 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
477 {
478     NTSTATUS ret;
479
480     SERVER_START_REQ( get_thread_context )
481     {
482         req->handle = handle;
483         req->flags = context->ContextFlags;
484         wine_server_add_data( req, context, sizeof(*context) );
485         wine_server_set_reply( req, context, sizeof(*context) );
486         ret = wine_server_call( req );
487     }
488     SERVER_END_REQ;
489     return ret;
490 }
491
492
493 /******************************************************************************
494  *              NtQueryInformationThread  (NTDLL.@)
495  *              ZwQueryInformationThread  (NTDLL.@)
496  */
497 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
498                                           void *data, ULONG length, ULONG *ret_len )
499 {
500     NTSTATUS status;
501
502     switch(class)
503     {
504     case ThreadBasicInformation:
505         {
506             THREAD_BASIC_INFORMATION info;
507
508             SERVER_START_REQ( get_thread_info )
509             {
510                 req->handle = handle;
511                 req->tid_in = 0;
512                 if (!(status = wine_server_call( req )))
513                 {
514                     info.ExitStatus             = reply->exit_code;
515                     info.TebBaseAddress         = reply->teb;
516                     info.ClientId.UniqueProcess = (HANDLE)reply->pid;
517                     info.ClientId.UniqueThread  = (HANDLE)reply->tid;
518                     info.AffinityMask           = reply->affinity;
519                     info.Priority               = reply->priority;
520                     info.BasePriority           = reply->priority;  /* FIXME */
521                 }
522             }
523             SERVER_END_REQ;
524             if (status == STATUS_SUCCESS)
525             {
526                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
527                 if (ret_len) *ret_len = min( length, sizeof(info) );
528             }
529         }
530         return status;
531     case ThreadTimes:
532     case ThreadPriority:
533     case ThreadBasePriority:
534     case ThreadAffinityMask:
535     case ThreadImpersonationToken:
536     case ThreadDescriptorTableEntry:
537     case ThreadEnableAlignmentFaultFixup:
538     case ThreadEventPair_Reusable:
539     case ThreadQuerySetWin32StartAddress:
540     case ThreadZeroTlsCell:
541     case ThreadPerformanceCount:
542     case ThreadAmILastThread:
543     case ThreadIdealProcessor:
544     case ThreadPriorityBoost:
545     case ThreadSetTlsArrayAddress:
546     case ThreadIsIoPending:
547     default:
548         FIXME( "info class %d not supported yet\n", class );
549         return STATUS_NOT_IMPLEMENTED;
550     }
551 }
552
553
554 /******************************************************************************
555  *              NtSetInformationThread  (NTDLL.@)
556  *              ZwSetInformationThread  (NTDLL.@)
557  */
558 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
559                                         LPCVOID data, ULONG length )
560 {
561     NTSTATUS status;
562     switch(class)
563     {
564     case ThreadZeroTlsCell:
565         if (handle == GetCurrentThread())
566         {
567             LIST_ENTRY *entry;
568             DWORD index;
569
570             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
571             index = *(const DWORD *)data;
572             if (index < TLS_MINIMUM_AVAILABLE)
573             {
574                 RtlAcquirePebLock();
575                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
576                 {
577                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
578                     teb->TlsSlots[index] = 0;
579                 }
580                 RtlReleasePebLock();
581             }
582             else
583             {
584                 index -= TLS_MINIMUM_AVAILABLE;
585                 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
586                     return STATUS_INVALID_PARAMETER;
587                 RtlAcquirePebLock();
588                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
589                 {
590                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
591                     if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
592                 }
593                 RtlReleasePebLock();
594             }
595             return STATUS_SUCCESS;
596         }
597         FIXME( "ZeroTlsCell not supported on other threads\n" );
598         return STATUS_NOT_IMPLEMENTED;
599
600     case ThreadImpersonationToken:
601         {
602             const HANDLE *phToken = data;
603             if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
604             TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
605             SERVER_START_REQ( set_thread_info )
606             {
607                 req->handle   = handle;
608                 req->token    = *phToken;
609                 req->mask     = SET_THREAD_INFO_TOKEN;
610                 status = wine_server_call( req );
611             }
612             SERVER_END_REQ;
613             return status;
614         }
615     case ThreadBasicInformation:
616     case ThreadTimes:
617     case ThreadPriority:
618     case ThreadBasePriority:
619     case ThreadAffinityMask:
620     case ThreadDescriptorTableEntry:
621     case ThreadEnableAlignmentFaultFixup:
622     case ThreadEventPair_Reusable:
623     case ThreadQuerySetWin32StartAddress:
624     case ThreadPerformanceCount:
625     case ThreadAmILastThread:
626     case ThreadIdealProcessor:
627     case ThreadPriorityBoost:
628     case ThreadSetTlsArrayAddress:
629     case ThreadIsIoPending:
630     default:
631         FIXME( "info class %d not supported yet\n", class );
632         return STATUS_NOT_IMPLEMENTED;
633     }
634 }
635
636
637 /**********************************************************************
638  *           NtCurrentTeb   (NTDLL.@)
639  */
640 #if defined(__i386__) && defined(__GNUC__)
641
642 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
643
644 #elif defined(__i386__) && defined(_MSC_VER)
645
646 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
647
648 #else
649
650 /**********************************************************************/
651
652 TEB * WINAPI NtCurrentTeb(void)
653 {
654     return wine_pthread_get_current_teb();
655 }
656
657 #endif  /* __i386__ */