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