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