Prevent crash when no URL is specified.
[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->exit_code   = STILL_ACTIVE;
266     teb->request_fd  = request_pipe[1];
267     teb->reply_fd    = -1;
268     teb->wait_fd[0]  = -1;
269     teb->wait_fd[1]  = -1;
270     teb->htask16     = NtCurrentTeb()->htask16;
271
272     info->pthread_info.teb_base = teb;
273     NtAllocateVirtualMemory( NtCurrentProcess(), &info->pthread_info.teb_base, 0, &size,
274                              MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
275     info->pthread_info.teb_size = size;
276     info->pthread_info.teb_sel  = teb->teb_sel;
277
278     if (!stack_reserve || !stack_commit)
279     {
280         IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
281         if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
282         if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
283     }
284     if (stack_reserve < stack_commit) stack_reserve = stack_commit;
285     stack_reserve = (stack_reserve + 0xffff) & ~0xffff;  /* round to 64K boundary */
286     if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024;  /* Xlib needs a large stack */
287
288     info->pthread_info.stack_base = NULL;
289     info->pthread_info.stack_size = stack_reserve;
290     info->pthread_info.entry      = start_thread;
291     info->entry_point             = start;
292     info->entry_arg               = param;
293
294     if (wine_pthread_create_thread( &info->pthread_info ) == -1)
295     {
296         status = STATUS_NO_MEMORY;
297         goto error;
298     }
299
300     if (id) id->UniqueThread = (HANDLE)tid;
301     if (handle_ptr) *handle_ptr = handle;
302     else NtClose( handle );
303
304     return STATUS_SUCCESS;
305
306 error:
307     if (teb) free_teb( teb );
308     if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
309     if (handle) NtClose( handle );
310     close( request_pipe[1] );
311     return status;
312 }
313
314
315 /***********************************************************************
316  *              NtOpenThread   (NTDLL.@)
317  *              ZwOpenThread   (NTDLL.@)
318  */
319 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
320                               const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
321 {
322     NTSTATUS ret;
323
324     SERVER_START_REQ( open_thread )
325     {
326         req->tid     = (thread_id_t)id->UniqueThread;
327         req->access  = access;
328         req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
329         ret = wine_server_call( req );
330         *handle = reply->handle;
331     }
332     SERVER_END_REQ;
333     return ret;
334 }
335
336
337 /******************************************************************************
338  *              NtSuspendThread   (NTDLL.@)
339  *              ZwSuspendThread   (NTDLL.@)
340  */
341 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
342 {
343     NTSTATUS ret;
344
345     SERVER_START_REQ( suspend_thread )
346     {
347         req->handle = handle;
348         if (!(ret = wine_server_call( req ))) *count = reply->count;
349     }
350     SERVER_END_REQ;
351     return ret;
352 }
353
354
355 /******************************************************************************
356  *              NtResumeThread   (NTDLL.@)
357  *              ZwResumeThread   (NTDLL.@)
358  */
359 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
360 {
361     NTSTATUS ret;
362
363     SERVER_START_REQ( resume_thread )
364     {
365         req->handle = handle;
366         if (!(ret = wine_server_call( req ))) *count = reply->count;
367     }
368     SERVER_END_REQ;
369     return ret;
370 }
371
372
373 /******************************************************************************
374  *              NtTerminateThread  (NTDLL.@)
375  *              ZwTerminateThread  (NTDLL.@)
376  */
377 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
378 {
379     NTSTATUS ret;
380     BOOL self, last;
381
382     SERVER_START_REQ( terminate_thread )
383     {
384         req->handle    = handle;
385         req->exit_code = exit_code;
386         ret = wine_server_call( req );
387         self = !ret && reply->self;
388         last = reply->last;
389     }
390     SERVER_END_REQ;
391
392     if (self)
393     {
394         if (last) exit( exit_code );
395         else server_abort_thread( exit_code );
396     }
397     return ret;
398 }
399
400
401 /******************************************************************************
402  *              NtQueueApcThread  (NTDLL.@)
403  */
404 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
405                                   ULONG_PTR arg2, ULONG_PTR arg3 )
406 {
407     NTSTATUS ret;
408     SERVER_START_REQ( queue_apc )
409     {
410         req->handle = handle;
411         req->user   = 1;
412         req->func   = func;
413         req->arg1   = (void *)arg1;
414         req->arg2   = (void *)arg2;
415         req->arg3   = (void *)arg3;
416         ret = wine_server_call( req );
417     }
418     SERVER_END_REQ;
419     return ret;
420 }
421
422
423 /***********************************************************************
424  *              NtSetContextThread  (NTDLL.@)
425  *              ZwSetContextThread  (NTDLL.@)
426  */
427 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
428 {
429     NTSTATUS ret;
430
431     SERVER_START_REQ( set_thread_context )
432     {
433         req->handle = handle;
434         req->flags  = context->ContextFlags;
435         wine_server_add_data( req, context, sizeof(*context) );
436         ret = wine_server_call( req );
437     }
438     SERVER_END_REQ;
439     return ret;
440 }
441
442
443 /***********************************************************************
444  *              NtGetContextThread  (NTDLL.@)
445  *              ZwGetContextThread  (NTDLL.@)
446  */
447 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
448 {
449     NTSTATUS ret;
450
451     SERVER_START_REQ( get_thread_context )
452     {
453         req->handle = handle;
454         req->flags = context->ContextFlags;
455         wine_server_add_data( req, context, sizeof(*context) );
456         wine_server_set_reply( req, context, sizeof(*context) );
457         ret = wine_server_call( req );
458     }
459     SERVER_END_REQ;
460     return ret;
461 }
462
463
464 /******************************************************************************
465  *              NtQueryInformationThread  (NTDLL.@)
466  *              ZwQueryInformationThread  (NTDLL.@)
467  */
468 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
469                                           void *data, ULONG length, ULONG *ret_len )
470 {
471     NTSTATUS status;
472
473     switch(class)
474     {
475     case ThreadBasicInformation:
476         {
477             THREAD_BASIC_INFORMATION info;
478
479             SERVER_START_REQ( get_thread_info )
480             {
481                 req->handle = handle;
482                 req->tid_in = 0;
483                 if (!(status = wine_server_call( req )))
484                 {
485                     info.ExitStatus             = reply->exit_code;
486                     info.TebBaseAddress         = reply->teb;
487                     info.ClientId.UniqueProcess = (HANDLE)reply->pid;
488                     info.ClientId.UniqueThread  = (HANDLE)reply->tid;
489                     info.AffinityMask           = reply->affinity;
490                     info.Priority               = reply->priority;
491                     info.BasePriority           = reply->priority;  /* FIXME */
492                 }
493             }
494             SERVER_END_REQ;
495             if (status == STATUS_SUCCESS)
496             {
497                 if (data) memcpy( data, &info, min( length, sizeof(info) ));
498                 if (ret_len) *ret_len = min( length, sizeof(info) );
499             }
500         }
501         return status;
502     case ThreadTimes:
503     case ThreadPriority:
504     case ThreadBasePriority:
505     case ThreadAffinityMask:
506     case ThreadImpersonationToken:
507     case ThreadDescriptorTableEntry:
508     case ThreadEnableAlignmentFaultFixup:
509     case ThreadEventPair_Reusable:
510     case ThreadQuerySetWin32StartAddress:
511     case ThreadZeroTlsCell:
512     case ThreadPerformanceCount:
513     case ThreadAmILastThread:
514     case ThreadIdealProcessor:
515     case ThreadPriorityBoost:
516     case ThreadSetTlsArrayAddress:
517     case ThreadIsIoPending:
518     default:
519         FIXME( "info class %d not supported yet\n", class );
520         return STATUS_NOT_IMPLEMENTED;
521     }
522 }
523
524
525 /******************************************************************************
526  *              NtSetInformationThread  (NTDLL.@)
527  *              ZwSetInformationThread  (NTDLL.@)
528  */
529 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
530                                         LPCVOID data, ULONG length )
531 {
532     switch(class)
533     {
534     case ThreadZeroTlsCell:
535         if (handle == GetCurrentThread())
536         {
537             LIST_ENTRY *entry;
538             DWORD index;
539
540             if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
541             index = *(const DWORD *)data;
542             if (index < TLS_MINIMUM_AVAILABLE)
543             {
544                 RtlAcquirePebLock();
545                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
546                 {
547                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
548                     teb->TlsSlots[index] = 0;
549                 }
550                 RtlReleasePebLock();
551             }
552             else
553             {
554                 index -= TLS_MINIMUM_AVAILABLE;
555                 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
556                     return STATUS_INVALID_PARAMETER;
557                 RtlAcquirePebLock();
558                 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
559                 {
560                     TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
561                     if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
562                 }
563                 RtlReleasePebLock();
564             }
565             return STATUS_SUCCESS;
566         }
567         FIXME( "ZeroTlsCell not supported on other threads\n" );
568         return STATUS_NOT_IMPLEMENTED;
569
570     case ThreadImpersonationToken:
571         {
572             const HANDLE *phToken = data;
573             if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
574             FIXME("Set ThreadImpersonationToken handle to %p\n", *phToken );
575             return STATUS_SUCCESS;
576         }
577     case ThreadBasicInformation:
578     case ThreadTimes:
579     case ThreadPriority:
580     case ThreadBasePriority:
581     case ThreadAffinityMask:
582     case ThreadDescriptorTableEntry:
583     case ThreadEnableAlignmentFaultFixup:
584     case ThreadEventPair_Reusable:
585     case ThreadQuerySetWin32StartAddress:
586     case ThreadPerformanceCount:
587     case ThreadAmILastThread:
588     case ThreadIdealProcessor:
589     case ThreadPriorityBoost:
590     case ThreadSetTlsArrayAddress:
591     case ThreadIsIoPending:
592     default:
593         FIXME( "info class %d not supported yet\n", class );
594         return STATUS_NOT_IMPLEMENTED;
595     }
596 }
597
598
599 /**********************************************************************
600  *           NtCurrentTeb   (NTDLL.@)
601  */
602 #if defined(__i386__) && defined(__GNUC__)
603
604 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
605
606 #elif defined(__i386__) && defined(_MSC_VER)
607
608 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
609
610 #else
611
612 /**********************************************************************/
613
614 TEB * WINAPI NtCurrentTeb(void)
615 {
616     return wine_pthread_get_current_teb();
617 }
618
619 #endif  /* __i386__ */