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