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