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