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