A couple of optimizations and bug fixes.
[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 RTL_BITMAP tls_bitmap;
52 static LIST_ENTRY tls_links;
53
54
55 /***********************************************************************
56  *           alloc_teb
57  */
58 static TEB *alloc_teb( ULONG *size )
59 {
60     TEB *teb;
61
62     *size = SIGNAL_STACK_SIZE + sizeof(TEB);
63     teb = wine_anon_mmap( NULL, *size, PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
64     if (teb == (TEB *)-1) return NULL;
65     if (!(teb->teb_sel = wine_ldt_alloc_fs()))
66     {
67         munmap( teb, *size );
68         return NULL;
69     }
70     teb->Tib.ExceptionList = (void *)~0UL;
71     teb->Tib.StackBase     = (void *)~0UL;
72     teb->Tib.Self          = &teb->Tib;
73     teb->Peb               = &peb;
74     teb->StaticUnicodeString.Buffer        = teb->StaticUnicodeBuffer;
75     teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
76     return teb;
77 }
78
79
80 /***********************************************************************
81  *           free_teb
82  */
83 static inline void free_teb( TEB *teb )
84 {
85     ULONG size = 0;
86     void *addr = teb;
87
88     NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
89     wine_ldt_free_fs( teb->teb_sel );
90     munmap( teb, SIGNAL_STACK_SIZE + sizeof(TEB) );
91 }
92
93
94 /***********************************************************************
95  *           thread_init
96  *
97  * Setup the initial thread.
98  *
99  * NOTES: The first allocated TEB on NT is at 0x7ffde000.
100  */
101 void thread_init(void)
102 {
103     TEB *teb;
104     void *addr;
105     ULONG size;
106     struct wine_pthread_thread_info thread_info;
107     static struct debug_info debug_info;  /* debug info for initial thread */
108
109     peb.ProcessParameters = &params;
110     peb.TlsBitmap         = &tls_bitmap;
111     peb.LdrData           = &ldr;
112     RtlInitializeBitMap( &tls_bitmap, (BYTE *)peb.TlsBitmapBits, sizeof(peb.TlsBitmapBits) * 8 );
113     InitializeListHead( &ldr.InLoadOrderModuleList );
114     InitializeListHead( &ldr.InMemoryOrderModuleList );
115     InitializeListHead( &ldr.InInitializationOrderModuleList );
116     InitializeListHead( &tls_links );
117
118     teb = alloc_teb( &size );
119     teb->tibflags      = TEBF_WIN32;
120     teb->request_fd    = -1;
121     teb->reply_fd      = -1;
122     teb->wait_fd[0]    = -1;
123     teb->wait_fd[1]    = -1;
124     teb->debug_info    = &debug_info;
125     InsertHeadList( &tls_links, &teb->TlsLinks );
126
127     thread_info.stack_base = NULL;
128     thread_info.stack_size = 0;
129     thread_info.teb_base   = teb;
130     thread_info.teb_size   = size;
131     thread_info.teb_sel    = teb->teb_sel;
132     wine_pthread_init_current_teb( &thread_info );
133     wine_pthread_init_thread( &thread_info );
134
135     debug_info.str_pos = debug_info.strings;
136     debug_info.out_pos = debug_info.output;
137     debug_init();
138     virtual_init();
139
140     /* setup the server connection */
141     server_init_process();
142     server_init_thread( thread_info.pid, thread_info.tid, NULL );
143
144     /* create a memory view for the TEB */
145     NtAllocateVirtualMemory( GetCurrentProcess(), &addr, teb, &size,
146                              MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
147
148     /* create the process heap */
149     if (!(peb.ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
150     {
151         MESSAGE( "wine: failed to create the process heap\n" );
152         exit(1);
153     }
154 }
155
156
157 /***********************************************************************
158  *           start_thread
159  *
160  * Startup routine for a newly created thread.
161  */
162 static void start_thread( struct wine_pthread_thread_info *info )
163 {
164     TEB *teb = info->teb_base;
165     struct startup_info *startup_info = (struct startup_info *)info;
166     PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
167     void *arg = startup_info->entry_arg;
168     struct debug_info debug_info;
169     ULONG size;
170
171     debug_info.str_pos = debug_info.strings;
172     debug_info.out_pos = debug_info.output;
173     teb->debug_info = &debug_info;
174
175     wine_pthread_init_current_teb( info );
176     SIGNAL_Init();
177     server_init_thread( info->pid, info->tid, func );
178     wine_pthread_init_thread( info );
179
180     /* allocate a memory view for the stack */
181     size = info->stack_size;
182     NtAllocateVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, info->stack_base,
183                              &size, MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
184     /* limit is lower than base since the stack grows down */
185     teb->Tib.StackBase  = (char *)info->stack_base + info->stack_size;
186     teb->Tib.StackLimit = info->stack_base;
187
188     /* setup the guard page */
189     size = 1;
190     NtProtectVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size,
191                             PAGE_EXECUTE_READWRITE | PAGE_GUARD, NULL );
192     RtlFreeHeap( GetProcessHeap(), 0, info );
193
194     RtlAcquirePebLock();
195     InsertHeadList( &tls_links, &teb->TlsLinks );
196     RtlReleasePebLock();
197
198     func( arg );
199 }
200
201
202 /***********************************************************************
203  *              RtlCreateUserThread   (NTDLL.@)
204  */
205 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
206                                      BOOLEAN suspended, PVOID stack_addr,
207                                      SIZE_T stack_reserve, SIZE_T stack_commit,
208                                      PRTL_THREAD_START_ROUTINE start, void *param,
209                                      HANDLE *handle_ptr, CLIENT_ID *id )
210 {
211     struct startup_info *info = NULL;
212     HANDLE handle = 0;
213     TEB *teb = NULL;
214     DWORD tid = 0;
215     ULONG size;
216     int request_pipe[2];
217     NTSTATUS status;
218
219     if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
220     fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
221     wine_server_send_fd( request_pipe[0] );
222
223     SERVER_START_REQ( new_thread )
224     {
225         req->suspend    = suspended;
226         req->inherit    = 0;  /* FIXME */
227         req->request_fd = request_pipe[0];
228         if (!(status = wine_server_call( req )))
229         {
230             handle = reply->handle;
231             tid = reply->tid;
232         }
233         close( request_pipe[0] );
234     }
235     SERVER_END_REQ;
236
237     if (status) goto error;
238
239     if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
240     {
241         status = STATUS_NO_MEMORY;
242         goto error;
243     }
244
245     if (!(teb = alloc_teb( &size )))
246     {
247         status = STATUS_NO_MEMORY;
248         goto error;
249     }
250     teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
251     teb->ClientId.UniqueThread  = (HANDLE)tid;
252
253     teb->tibflags    = TEBF_WIN32;
254     teb->exit_code   = STILL_ACTIVE;
255     teb->request_fd  = request_pipe[1];
256     teb->reply_fd    = -1;
257     teb->wait_fd[0]  = -1;
258     teb->wait_fd[1]  = -1;
259     teb->htask16     = NtCurrentTeb()->htask16;
260
261     NtAllocateVirtualMemory( GetCurrentProcess(), &info->pthread_info.teb_base, teb, &size,
262                              MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
263     info->pthread_info.teb_size = size;
264     info->pthread_info.teb_sel  = teb->teb_sel;
265
266     if (!stack_reserve || !stack_commit)
267     {
268         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
269         if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
270         if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
271     }
272     if (stack_reserve < stack_commit) stack_reserve = stack_commit;
273     stack_reserve = (stack_reserve + 0xffff) & ~0xffff;  /* round to 64K boundary */
274     if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024;  /* Xlib needs a large stack */
275
276     info->pthread_info.stack_base = NULL;
277     info->pthread_info.stack_size = stack_reserve;
278     info->pthread_info.entry      = start_thread;
279     info->entry_point             = start;
280     info->entry_arg               = param;
281
282     if (wine_pthread_create_thread( &info->pthread_info ) == -1)
283     {
284         status = STATUS_NO_MEMORY;
285         goto error;
286     }
287
288     if (id) id->UniqueThread = (HANDLE)tid;
289     if (handle_ptr) *handle_ptr = handle;
290     else NtClose( handle );
291
292     return STATUS_SUCCESS;
293
294 error:
295     if (teb) free_teb( teb );
296     if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
297     if (handle) NtClose( handle );
298     close( request_pipe[1] );
299     return status;
300 }
301
302
303 /***********************************************************************
304  *              NtOpenThread   (NTDLL.@)
305  *              ZwOpenThread   (NTDLL.@)
306  */
307 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
308                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
309 {
310     NTSTATUS ret;
311
312     SERVER_START_REQ( open_thread )
313     {
314         req->tid     = (thread_id_t)id->UniqueThread;
315         req->access  = access;
316         req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
317         ret = wine_server_call( req );
318         *handle = reply->handle;
319     }
320     SERVER_END_REQ;
321     return ret;
322 }
323
324
325 /******************************************************************************
326  *              NtSuspendThread   (NTDLL.@)
327  *              ZwSuspendThread   (NTDLL.@)
328  */
329 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
330 {
331     NTSTATUS ret;
332
333     SERVER_START_REQ( suspend_thread )
334     {
335         req->handle = handle;
336         if (!(ret = wine_server_call( req ))) *count = reply->count;
337     }
338     SERVER_END_REQ;
339     return ret;
340 }
341
342
343 /******************************************************************************
344  *              NtResumeThread   (NTDLL.@)
345  *              ZwResumeThread   (NTDLL.@)
346  */
347 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
348 {
349     NTSTATUS ret;
350
351     SERVER_START_REQ( resume_thread )
352     {
353         req->handle = handle;
354         if (!(ret = wine_server_call( req ))) *count = reply->count;
355     }
356     SERVER_END_REQ;
357     return ret;
358 }
359
360
361 /******************************************************************************
362  *              NtTerminateThread  (NTDLL.@)
363  *              ZwTerminateThread  (NTDLL.@)
364  */
365 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
366 {
367     NTSTATUS ret;
368     BOOL self, last;
369
370     SERVER_START_REQ( terminate_thread )
371     {
372         req->handle    = handle;
373         req->exit_code = exit_code;
374         ret = wine_server_call( req );
375         self = !ret && reply->self;
376         last = reply->last;
377     }
378     SERVER_END_REQ;
379
380     if (self)
381     {
382         if (last) exit( exit_code );
383         else server_abort_thread( exit_code );
384     }
385     return ret;
386 }
387
388
389 /******************************************************************************
390  *              NtQueueApcThread  (NTDLL.@)
391  */
392 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
393                                   ULONG_PTR arg2, ULONG_PTR arg3 )
394 {
395     NTSTATUS ret;
396     SERVER_START_REQ( queue_apc )
397     {
398         req->handle = handle;
399         req->user   = 1;
400         req->func   = func;
401         req->arg1   = (void *)arg1;
402         req->arg2   = (void *)arg2;
403         req->arg3   = (void *)arg3;
404         ret = wine_server_call( req );
405     }
406     SERVER_END_REQ;
407     return ret;
408 }
409
410
411 /***********************************************************************
412  *              NtSetContextThread  (NTDLL.@)
413  *              ZwSetContextThread  (NTDLL.@)
414  */
415 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
416 {
417     NTSTATUS ret;
418
419     SERVER_START_REQ( set_thread_context )
420     {
421         req->handle = handle;
422         req->flags  = context->ContextFlags;
423         wine_server_add_data( req, context, sizeof(*context) );
424         ret = wine_server_call( req );
425     }
426     SERVER_END_REQ;
427     return ret;
428 }
429
430
431 /***********************************************************************
432  *              NtGetContextThread  (NTDLL.@)
433  *              ZwGetContextThread  (NTDLL.@)
434  */
435 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
436 {
437     NTSTATUS ret;
438
439     SERVER_START_REQ( get_thread_context )
440     {
441         req->handle = handle;
442         req->flags = context->ContextFlags;
443         wine_server_add_data( req, context, sizeof(*context) );
444         wine_server_set_reply( req, context, sizeof(*context) );
445         ret = wine_server_call( req );
446     }
447     SERVER_END_REQ;
448     return ret;
449 }
450
451
452 /******************************************************************************
453  *              NtQueryInformationThread  (NTDLL.@)
454  *              ZwQueryInformationThread  (NTDLL.@)
455  */
456 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
457                                           void *data, ULONG length, ULONG *ret_len )
458 {
459     NTSTATUS status;
460
461     switch(class)
462     {
463     case ThreadBasicInformation:
464         {
465             THREAD_BASIC_INFORMATION info;
466
467             SERVER_START_REQ( get_thread_info )
468             {
469                 req->handle = handle;
470                 req->tid_in = 0;
471                 if (!(status = wine_server_call( req )))
472                 {
473                     info.ExitStatus             = reply->exit_code;
474                     info.TebBaseAddress         = reply->teb;
475                     info.ClientId.UniqueProcess = (HANDLE)reply->pid;
476                     info.ClientId.UniqueThread  = (HANDLE)reply->tid;
477                     info.AffinityMask           = reply->affinity;
478                     info.Priority               = reply->priority;
479                     info.BasePriority           = reply->priority;  /* FIXME */
480                 }
481             }
482             SERVER_END_REQ;
483             if (status == STATUS_SUCCESS)
484             {
485                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
486                 if (ret_len) *ret_len = min( length, sizeof(info) );
487             }
488         }
489         return status;
490     case ThreadTimes:
491     case ThreadPriority:
492     case ThreadBasePriority:
493     case ThreadAffinityMask:
494     case ThreadImpersonationToken:
495     case ThreadDescriptorTableEntry:
496     case ThreadEnableAlignmentFaultFixup:
497     case ThreadEventPair_Reusable:
498     case ThreadQuerySetWin32StartAddress:
499     case ThreadZeroTlsCell:
500     case ThreadPerformanceCount:
501     case ThreadAmILastThread:
502     case ThreadIdealProcessor:
503     case ThreadPriorityBoost:
504     case ThreadSetTlsArrayAddress:
505     case ThreadIsIoPending:
506     default:
507         FIXME( "info class %d not supported yet\n", class );
508         return STATUS_NOT_IMPLEMENTED;
509     }
510 }
511
512
513 /******************************************************************************
514  *              NtSetInformationThread  (NTDLL.@)
515  *              ZwSetInformationThread  (NTDLL.@)
516  */
517 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
518                                         LPCVOID data, ULONG length )
519 {
520     switch(class)
521     {
522     case ThreadZeroTlsCell:
523         if (handle == GetCurrentThread())
524         {
525             LIST_ENTRY *entry;
526             DWORD index;
527
528             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
529             index = *(DWORD *)data;
530             if (index >= 64) return STATUS_INVALID_PARAMETER;
531             RtlAcquirePebLock();
532             for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
533             {
534                 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
535                 teb->TlsSlots[index] = 0;
536             }
537             RtlReleasePebLock();
538             return STATUS_SUCCESS;
539         }
540         FIXME( "ZeroTlsCell not supported on other threads\n" );
541         return STATUS_NOT_IMPLEMENTED;
542
543     case ThreadBasicInformation:
544     case ThreadTimes:
545     case ThreadPriority:
546     case ThreadBasePriority:
547     case ThreadAffinityMask:
548     case ThreadImpersonationToken:
549     case ThreadDescriptorTableEntry:
550     case ThreadEnableAlignmentFaultFixup:
551     case ThreadEventPair_Reusable:
552     case ThreadQuerySetWin32StartAddress:
553     case ThreadPerformanceCount:
554     case ThreadAmILastThread:
555     case ThreadIdealProcessor:
556     case ThreadPriorityBoost:
557     case ThreadSetTlsArrayAddress:
558     case ThreadIsIoPending:
559     default:
560         FIXME( "info class %d not supported yet\n", class );
561         return STATUS_NOT_IMPLEMENTED;
562     }
563 }
564
565
566 /**********************************************************************
567  *           NtCurrentTeb   (NTDLL.@)
568  */
569 #if defined(__i386__) && defined(__GNUC__)
570 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
571 #elif defined(__i386__) && defined(_MSC_VER)
572 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
573 #else
574 TEB * WINAPI NtCurrentTeb(void)
575 {
576     return wine_pthread_get_current_teb();
577 }
578 #endif  /* __i386__ */