Debian Codegraph @

libphobos/libdruntime/core/thread/osthread.d

raw
1 /**
2 * The osthread module provides low-level, OS-dependent code
3 * for thread creation and management.
4 *
5 * Copyright: Copyright Sean Kelly 2005 - 2012.
6 * License: Distributed under the
7 * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
8 * (See accompanying file LICENSE)
9 * Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak
10 * Source: $(DRUNTIMESRC core/thread/osthread.d)
11 */
12
13 module core.thread.osthread;
14
15 import core.atomic;
16 import core.exception : onOutOfMemoryError;
17 import core.internal.traits : externDFunc;
18 import core.memory : GC, pageSize;
19 import core.thread.context;
20 import core.thread.threadbase;
21 import core.thread.types;
22 import core.time;
23
24 ///////////////////////////////////////////////////////////////////////////////
25 // Platform Detection and Memory Allocation
26 ///////////////////////////////////////////////////////////////////////////////
27
28 version (OSX)
29 version = Darwin;
30 else version (iOS)
31 version = Darwin;
32 else version (TVOS)
33 version = Darwin;
34 else version (WatchOS)
35 version = Darwin;
36
37 version (D_InlineAsm_X86)
38 {
39 version (Windows)
40 version = AsmX86_Windows;
41 else version (Posix)
42 version = AsmX86_Posix;
43 }
44 else version (D_InlineAsm_X86_64)
45 {
46 version (Windows)
47 {
48 version = AsmX86_64_Windows;
49 }
50 else version (Posix)
51 {
52 version = AsmX86_64_Posix;
53 }
54 }
55
56 version (Windows)
57 {
58 import core.stdc.stdint : uintptr_t; // for _beginthreadex decl below
59 import core.stdc.stdlib : free, malloc, realloc;
60 import core.sys.windows.basetsd /+: HANDLE+/;
61 import core.sys.windows.threadaux /+: getThreadStackBottom, impersonate_thread, OpenThreadHandle+/;
62 import core.sys.windows.winbase /+: CloseHandle, CREATE_SUSPENDED, DuplicateHandle, GetCurrentThread,
63 GetCurrentThreadId, GetCurrentProcess, GetExitCodeThread, GetSystemInfo, GetThreadContext,
64 GetThreadPriority, INFINITE, ResumeThread, SetThreadPriority, Sleep, STILL_ACTIVE,
65 SuspendThread, SwitchToThread, SYSTEM_INFO, THREAD_PRIORITY_IDLE, THREAD_PRIORITY_NORMAL,
66 THREAD_PRIORITY_TIME_CRITICAL, WAIT_OBJECT_0, WaitForSingleObject+/;
67 import core.sys.windows.windef /+: TRUE+/;
68 import core.sys.windows.winnt /+: CONTEXT, CONTEXT_CONTROL, CONTEXT_INTEGER+/;
69
70 private extern (Windows) alias btex_fptr = uint function(void*);
71 private extern (C) uintptr_t _beginthreadex(void*, uint, btex_fptr, void*, uint, uint*) nothrow @nogc;
72 }
73 else version (Posix)
74 {
75 static import core.sys.posix.pthread;
76 static import core.sys.posix.signal;
77 import core.stdc.errno : EINTR, errno;
78 import core.sys.posix.pthread : pthread_atfork, pthread_attr_destroy, pthread_attr_getstack, pthread_attr_init,
79 pthread_attr_setstacksize, pthread_create, pthread_detach, pthread_getschedparam, pthread_join, pthread_self,
80 pthread_setschedparam, sched_get_priority_max, sched_get_priority_min, sched_param, sched_yield;
81 import core.sys.posix.semaphore : sem_init, sem_post, sem_t, sem_wait;
82 import core.sys.posix.signal : pthread_kill, sigaction, sigaction_t, sigdelset, sigfillset, sigset_t, sigsuspend,
83 SIGUSR1, stack_t;
84 import core.sys.posix.stdlib : free, malloc, realloc;
85 import core.sys.posix.sys.types : pthread_attr_t, pthread_key_t, pthread_t;
86 import core.sys.posix.time : nanosleep, timespec;
87
88 version (Darwin)
89 {
90 import core.sys.darwin.mach.kern_return : KERN_SUCCESS;
91 import core.sys.darwin.mach.port : mach_port_t;
92 import core.sys.darwin.mach.thread_act : mach_msg_type_number_t,
93 thread_get_state, thread_resume, thread_suspend;
94 import core.sys.darwin.pthread : pthread_mach_thread_np;
95 version (X86)
96 {
97 import core.sys.darwin.mach.thread_act :
98 x86_THREAD_STATE32, x86_THREAD_STATE32_COUNT, x86_thread_state32_t;
99 }
100 else version (X86_64)
101 {
102 import core.sys.darwin.mach.thread_act :
103 x86_THREAD_STATE64, x86_THREAD_STATE64_COUNT, x86_thread_state64_t;
104 }
105 else version (AArch64)
106 {
107 import core.sys.darwin.mach.thread_act :
108 ARM_THREAD_STATE64, ARM_THREAD_STATE64_COUNT, arm_thread_state64_t;
109 }
110 else version (PPC)
111 {
112 import core.sys.darwin.mach.thread_act :
113 PPC_THREAD_STATE32, PPC_THREAD_STATE32_COUNT, ppc_thread_state32_t;
114 }
115 else version (PPC64)
116 {
117 import core.sys.darwin.mach.thread_act :
118 PPC_THREAD_STATE64, PPC_THREAD_STATE64_COUNT, ppc_thread_state64_t;
119 }
120 }
121 }
122
123 version (Solaris)
124 {
125 import core.sys.posix.sys.wait : idtype_t;
126 import core.sys.solaris.sys.priocntl : PC_CLNULL, PC_GETCLINFO, PC_GETPARMS, PC_SETPARMS, pcinfo_t, pcparms_t, priocntl;
127 import core.sys.solaris.sys.types : P_MYID, pri_t;
128 }
129
130 version (GNU)
131 {
132 import gcc.builtins;
133 }
134
135 /**
136 * Hook for whatever EH implementation is used to save/restore some data
137 * per stack.
138 *
139 * Params:
140 * newContext = The return value of the prior call to this function
141 * where the stack was last swapped out, or null when a fiber stack
142 * is switched in for the first time.
143 */
144 private extern(C) void* _d_eh_swapContext(void* newContext) nothrow @nogc;
145
146 version (DigitalMars)
147 {
148 version (Windows)
149 {
150 extern(D) void* swapContext(void* newContext) nothrow @nogc
151 {
152 return _d_eh_swapContext(newContext);
153 }
154 }
155 else
156 {
157 extern(C) void* _d_eh_swapContextDwarf(void* newContext) nothrow @nogc;
158
159 extern(D) void* swapContext(void* newContext) nothrow @nogc
160 {
161 /* Detect at runtime which scheme is being used.
162 * Eventually, determine it statically.
163 */
164 static int which = 0;
165 final switch (which)
166 {
167 case 0:
168 {
169 assert(newContext == null);
170 auto p = _d_eh_swapContext(newContext);
171 auto pdwarf = _d_eh_swapContextDwarf(newContext);
172 if (p)
173 {
174 which = 1;
175 return p;
176 }
177 else if (pdwarf)
178 {
179 which = 2;
180 return pdwarf;
181 }
182 return null;
183 }
184 case 1:
185 return _d_eh_swapContext(newContext);
186 case 2:
187 return _d_eh_swapContextDwarf(newContext);
188 }
189 }
190 }
191 }
192 else
193 {
194 extern(D) void* swapContext(void* newContext) nothrow @nogc
195 {
196 return _d_eh_swapContext(newContext);
197 }
198 }
199
200 ///////////////////////////////////////////////////////////////////////////////
201 // Thread
202 ///////////////////////////////////////////////////////////////////////////////
203
204 /**
205 * This class encapsulates all threading functionality for the D
206 * programming language. As thread manipulation is a required facility
207 * for garbage collection, all user threads should derive from this
208 * class, and instances of this class should never be explicitly deleted.
209 * A new thread may be created using either derivation or composition, as
210 * in the following example.
211 */
212 class Thread : ThreadBase
213 {
214 //
215 // Standard thread data
216 //
217 version (Windows)
218 {
219 private HANDLE m_hndl;
220 }
221
222 version (Posix)
223 {
224 private shared bool m_isRunning;
225 }
226
227 version (Darwin)
228 {
229 private mach_port_t m_tmach;
230 }
231
232 version (Solaris)
233 {
234 private __gshared bool m_isRTClass;
235 }
236
237 //
238 // Standard types
239 //
240 version (Windows)
241 {
242 alias TLSKey = uint;
243 }
244 else version (Posix)
245 {
246 alias TLSKey = pthread_key_t;
247 }
248
249 ///////////////////////////////////////////////////////////////////////////
250 // Initialization
251 ///////////////////////////////////////////////////////////////////////////
252
253
254 /**
255 * Initializes a thread object which is associated with a static
256 * D function.
257 *
258 * Params:
259 * fn = The thread function.
260 * sz = The stack size for this thread.
261 *
262 * In:
263 * fn must not be null.
264 */
265 this( void function() fn, size_t sz = 0 ) @safe pure nothrow @nogc
266 {
267 super(fn, sz);
268 }
269
270
271 /**
272 * Initializes a thread object which is associated with a dynamic
273 * D function.
274 *
275 * Params:
276 * dg = The thread function.
277 * sz = The stack size for this thread.
278 *
279 * In:
280 * dg must not be null.
281 */
282 this( void delegate() dg, size_t sz = 0 ) @safe pure nothrow @nogc
283 {
284 super(dg, sz);
285 }
286
287 package this( size_t sz = 0 ) @safe pure nothrow @nogc
288 {
289 super(sz);
290 }
291
292 /**
293 * Cleans up any remaining resources used by this object.
294 */
295 ~this() nothrow @nogc
296 {
297 if (super.destructBeforeDtor())
298 return;
299
300 version (Windows)
301 {
302 m_addr = m_addr.init;
303 CloseHandle( m_hndl );
304 m_hndl = m_hndl.init;
305 }
306 else version (Posix)
307 {
308 if (m_addr != m_addr.init)
309 pthread_detach( m_addr );
310 m_addr = m_addr.init;
311 }
312 version (Darwin)
313 {
314 m_tmach = m_tmach.init;
315 }
316 }
317
318 //
319 // Thread entry point. Invokes the function or delegate passed on
320 // construction (if any).
321 //
322 private final void run()
323 {
324 super.run();
325 }
326
327 /**
328 * Provides a reference to the calling thread.
329 *
330 * Returns:
331 * The thread object representing the calling thread. The result of
332 * deleting this object is undefined. If the current thread is not
333 * attached to the runtime, a null reference is returned.
334 */
335 static Thread getThis() @safe nothrow @nogc
336 {
337 return ThreadBase.getThis().toThread;
338 }
339
340 ///////////////////////////////////////////////////////////////////////////
341 // Thread Context and GC Scanning Support
342 ///////////////////////////////////////////////////////////////////////////
343
344
345 version (Windows)
346 {
347 version (X86)
348 {
349 uint[8] m_reg; // edi,esi,ebp,esp,ebx,edx,ecx,eax
350 }
351 else version (X86_64)
352 {
353 ulong[16] m_reg; // rdi,rsi,rbp,rsp,rbx,rdx,rcx,rax
354 // r8,r9,r10,r11,r12,r13,r14,r15
355 }
356 else
357 {
358 static assert(false, "Architecture not supported." );
359 }
360 }
361 else version (Darwin)
362 {
363 version (X86)
364 {
365 uint[8] m_reg; // edi,esi,ebp,esp,ebx,edx,ecx,eax
366 }
367 else version (X86_64)
368 {
369 ulong[16] m_reg; // rdi,rsi,rbp,rsp,rbx,rdx,rcx,rax
370 // r8,r9,r10,r11,r12,r13,r14,r15
371 }
372 else version (AArch64)
373 {
374 ulong[33] m_reg; // x0-x31, pc
375 }
376 else version (ARM)
377 {
378 uint[16] m_reg; // r0-r15
379 }
380 else version (PPC)
381 {
382 // Make the assumption that we only care about non-fp and non-vr regs.
383 // ??? : it seems plausible that a valid address can be copied into a VR.
384 uint[32] m_reg; // r0-31
385 }
386 else version (PPC64)
387 {
388 // As above.
389 ulong[32] m_reg; // r0-31
390 }
391 else
392 {
393 static assert(false, "Architecture not supported." );
394 }
395 }
396
397
398 ///////////////////////////////////////////////////////////////////////////
399 // General Actions
400 ///////////////////////////////////////////////////////////////////////////
401
402
403 /**
404 * Starts the thread and invokes the function or delegate passed upon
405 * construction.
406 *
407 * In:
408 * This routine may only be called once per thread instance.
409 *
410 * Throws:
411 * ThreadException if the thread fails to start.
412 */
413 final Thread start() nothrow
414 in
415 {
416 assert( !next && !prev );
417 }
418 do
419 {
420 auto wasThreaded = multiThreadedFlag;
421 multiThreadedFlag = true;
422 scope( failure )
423 {
424 if ( !wasThreaded )
425 multiThreadedFlag = false;
426 }
427
428 version (Windows) {} else
429 version (Posix)
430 {
431 size_t stksz = adjustStackSize( m_sz );
432
433 pthread_attr_t attr;
434
435 if ( pthread_attr_init( &attr ) )
436 onThreadError( "Error initializing thread attributes" );
437 if ( stksz && pthread_attr_setstacksize( &attr, stksz ) )
438 onThreadError( "Error initializing thread stack size" );
439 }
440
441 version (Windows)
442 {
443 // NOTE: If a thread is just executing DllMain()
444 // while another thread is started here, it holds an OS internal
445 // lock that serializes DllMain with CreateThread. As the code
446 // might request a synchronization on slock (e.g. in thread_findByAddr()),
447 // we cannot hold that lock while creating the thread without
448 // creating a deadlock
449 //
450 // Solution: Create the thread in suspended state and then
451 // add and resume it with slock acquired
452 assert(m_sz <= uint.max, "m_sz must be less than or equal to uint.max");
453 m_hndl = cast(HANDLE) _beginthreadex( null, cast(uint) m_sz, &thread_entryPoint, cast(void*) this, CREATE_SUSPENDED, &m_addr );
454 if ( cast(size_t) m_hndl == 0 )
455 onThreadError( "Error creating thread" );
456 }
457
458 slock.lock_nothrow();
459 scope(exit) slock.unlock_nothrow();
460 {
461 incrementAboutToStart(this);
462
463 version (Windows)
464 {
465 if ( ResumeThread( m_hndl ) == -1 )
466 onThreadError( "Error resuming thread" );
467 }
468 else version (Posix)
469 {
470 // NOTE: This is also set to true by thread_entryPoint, but set it
471 // here as well so the calling thread will see the isRunning
472 // state immediately.
473 atomicStore!(MemoryOrder.raw)(m_isRunning, true);
474 scope( failure ) atomicStore!(MemoryOrder.raw)(m_isRunning, false);
475
476 version (Shared)
477 {
478 auto libs = externDFunc!("rt.sections_elf_shared.pinLoadedLibraries",
479 void* function() @nogc nothrow)();
480
481 auto ps = cast(void**).malloc(2 * size_t.sizeof);
482 if (ps is null) onOutOfMemoryError();
483 ps[0] = cast(void*)this;
484 ps[1] = cast(void*)libs;
485 if ( pthread_create( &m_addr, &attr, &thread_entryPoint, ps ) != 0 )
486 {
487 externDFunc!("rt.sections_elf_shared.unpinLoadedLibraries",
488 void function(void*) @nogc nothrow)(libs);
489 .free(ps);
490 onThreadError( "Error creating thread" );
491 }
492 }
493 else
494 {
495 if ( pthread_create( &m_addr, &attr, &thread_entryPoint, cast(void*) this ) != 0 )
496 onThreadError( "Error creating thread" );
497 }
498 if ( pthread_attr_destroy( &attr ) != 0 )
499 onThreadError( "Error destroying thread attributes" );
500 }
501 version (Darwin)
502 {
503 m_tmach = pthread_mach_thread_np( m_addr );
504 if ( m_tmach == m_tmach.init )
505 onThreadError( "Error creating thread" );
506 }
507
508 return this;
509 }
510 }
511
512 /**
513 * Waits for this thread to complete. If the thread terminated as the
514 * result of an unhandled exception, this exception will be rethrown.
515 *
516 * Params:
517 * rethrow = Rethrow any unhandled exception which may have caused this
518 * thread to terminate.
519 *
520 * Throws:
521 * ThreadException if the operation fails.
522 * Any exception not handled by the joined thread.
523 *
524 * Returns:
525 * Any exception not handled by this thread if rethrow = false, null
526 * otherwise.
527 */
528 override final Throwable join( bool rethrow = true )
529 {
530 version (Windows)
531 {
532 if ( m_addr != m_addr.init && WaitForSingleObject( m_hndl, INFINITE ) != WAIT_OBJECT_0 )
533 throw new ThreadException( "Unable to join thread" );
534 // NOTE: m_addr must be cleared before m_hndl is closed to avoid
535 // a race condition with isRunning. The operation is done
536 // with atomicStore to prevent compiler reordering.
537 atomicStore!(MemoryOrder.raw)(*cast(shared)&m_addr, m_addr.init);
538 CloseHandle( m_hndl );
539 m_hndl = m_hndl.init;
540 }
541 else version (Posix)
542 {
543 if ( m_addr != m_addr.init && pthread_join( m_addr, null ) != 0 )
544 throw new ThreadException( "Unable to join thread" );
545 // NOTE: pthread_join acts as a substitute for pthread_detach,
546 // which is normally called by the dtor. Setting m_addr
547 // to zero ensures that pthread_detach will not be called
548 // on object destruction.
549 m_addr = m_addr.init;
550 }
551 if ( m_unhandled )
552 {
553 if ( rethrow )
554 throw m_unhandled;
555 return m_unhandled;
556 }
557 return null;
558 }
559
560
561 ///////////////////////////////////////////////////////////////////////////
562 // Thread Priority Actions
563 ///////////////////////////////////////////////////////////////////////////
564
565 version (Windows)
566 {
567 @property static int PRIORITY_MIN() @nogc nothrow pure @safe
568 {
569 return THREAD_PRIORITY_IDLE;
570 }
571
572 @property static const(int) PRIORITY_MAX() @nogc nothrow pure @safe
573 {
574 return THREAD_PRIORITY_TIME_CRITICAL;
575 }
576
577 @property static int PRIORITY_DEFAULT() @nogc nothrow pure @safe
578 {
579 return THREAD_PRIORITY_NORMAL;
580 }
581 }
582 else
583 {
584 private struct Priority
585 {
586 int PRIORITY_MIN = int.min;
587 int PRIORITY_DEFAULT = int.min;
588 int PRIORITY_MAX = int.min;
589 }
590
591 /*
592 Lazily loads one of the members stored in a hidden global variable of
593 type `Priority`. Upon the first access of either member, the entire
594 `Priority` structure is initialized. Multiple initializations from
595 different threads calling this function are tolerated.
596
597 `which` must be one of `PRIORITY_MIN`, `PRIORITY_DEFAULT`,
598 `PRIORITY_MAX`.
599 */
600 private static shared Priority cache;
601 private static int loadGlobal(string which)()
602 {
603 auto local = atomicLoad(mixin("cache." ~ which));
604 if (local != local.min) return local;
605 // There will be benign races
606 cache = loadPriorities;
607 return atomicLoad(mixin("cache." ~ which));
608 }
609
610 /*
611 Loads all priorities and returns them as a `Priority` structure. This
612 function is thread-neutral.
613 */
614 private static Priority loadPriorities() @nogc nothrow @trusted
615 {
616 Priority result;
617 version (Solaris)
618 {
619 pcparms_t pcParms;
620 pcinfo_t pcInfo;
621
622 pcParms.pc_cid = PC_CLNULL;
623 if (priocntl(idtype_t.P_PID, P_MYID, PC_GETPARMS, &pcParms) == -1)
624 assert( 0, "Unable to get scheduling class" );
625
626 pcInfo.pc_cid = pcParms.pc_cid;
627 // PC_GETCLINFO ignores the first two args, use dummy values
628 if (priocntl(idtype_t.P_PID, 0, PC_GETCLINFO, &pcInfo) == -1)
629 assert( 0, "Unable to get scheduling class info" );
630
631 pri_t* clparms = cast(pri_t*)&pcParms.pc_clparms;
632 pri_t* clinfo = cast(pri_t*)&pcInfo.pc_clinfo;
633
634 result.PRIORITY_MAX = clparms[0];
635
636 if (pcInfo.pc_clname == "RT")
637 {
638 m_isRTClass = true;
639
640 // For RT class, just assume it can't be changed
641 result.PRIORITY_MIN = clparms[0];
642 result.PRIORITY_DEFAULT = clparms[0];
643 }
644 else
645 {
646 m_isRTClass = false;
647
648 // For all other scheduling classes, there are
649 // two key values -- uprilim and maxupri.
650 // maxupri is the maximum possible priority defined
651 // for the scheduling class, and valid priorities
652 // range are in [-maxupri, maxupri].
653 //
654 // However, uprilim is an upper limit that the
655 // current thread can set for the current scheduling
656 // class, which can be less than maxupri. As such,
657 // use this value for priorityMax since this is
658 // the effective maximum.
659
660 // maxupri
661 result.PRIORITY_MIN = -cast(int)(clinfo[0]);
662 // by definition
663 result.PRIORITY_DEFAULT = 0;
664 }
665 }
666 else version (Posix)
667 {
668 int policy;
669 sched_param param;
670 pthread_getschedparam( pthread_self(), &policy, &param ) == 0
671 || assert(0, "Internal error in pthread_getschedparam");
672
673 result.PRIORITY_MIN = sched_get_priority_min( policy );
674 result.PRIORITY_MIN != -1
675 || assert(0, "Internal error in sched_get_priority_min");
676 result.PRIORITY_DEFAULT = param.sched_priority;
677 result.PRIORITY_MAX = sched_get_priority_max( policy );
678 result.PRIORITY_MAX != -1 ||
679 assert(0, "Internal error in sched_get_priority_max");
680 }
681 else
682 {
683 static assert(0, "Your code here.");
684 }
685 return result;
686 }
687
688 /**
689 * The minimum scheduling priority that may be set for a thread. On
690 * systems where multiple scheduling policies are defined, this value
691 * represents the minimum valid priority for the scheduling policy of
692 * the process.
693 */
694 @property static int PRIORITY_MIN() @nogc nothrow pure @trusted
695 {
696 return (cast(int function() @nogc nothrow pure @safe)
697 &loadGlobal!"PRIORITY_MIN")();
698 }
699
700 /**
701 * The maximum scheduling priority that may be set for a thread. On
702 * systems where multiple scheduling policies are defined, this value
703 * represents the maximum valid priority for the scheduling policy of
704 * the process.
705 */
706 @property static const(int) PRIORITY_MAX() @nogc nothrow pure @trusted
707 {
708 return (cast(int function() @nogc nothrow pure @safe)
709 &loadGlobal!"PRIORITY_MAX")();
710 }
711
712 /**
713 * The default scheduling priority that is set for a thread. On
714 * systems where multiple scheduling policies are defined, this value
715 * represents the default priority for the scheduling policy of
716 * the process.
717 */
718 @property static int PRIORITY_DEFAULT() @nogc nothrow pure @trusted
719 {
720 return (cast(int function() @nogc nothrow pure @safe)
721 &loadGlobal!"PRIORITY_DEFAULT")();
722 }
723 }
724
725 version (NetBSD)
726 {
727 //NetBSD does not support priority for default policy
728 // and it is not possible change policy without root access
729 int fakePriority = int.max;
730 }
731
732 /**
733 * Gets the scheduling priority for the associated thread.
734 *
735 * Note: Getting the priority of a thread that already terminated
736 * might return the default priority.
737 *
738 * Returns:
739 * The scheduling priority of this thread.
740 */
741 final @property int priority()
742 {
743 version (Windows)
744 {
745 return GetThreadPriority( m_hndl );
746 }
747 else version (NetBSD)
748 {
749 return fakePriority==int.max? PRIORITY_DEFAULT : fakePriority;
750 }
751 else version (Posix)
752 {
753 int policy;
754 sched_param param;
755
756 if (auto err = pthread_getschedparam(m_addr, &policy, &param))
757 {
758 // ignore error if thread is not running => Bugzilla 8960
759 if (!atomicLoad(m_isRunning)) return PRIORITY_DEFAULT;
760 throw new ThreadException("Unable to get thread priority");
761 }
762 return param.sched_priority;
763 }
764 }
765
766
767 /**
768 * Sets the scheduling priority for the associated thread.
769 *
770 * Note: Setting the priority of a thread that already terminated
771 * might have no effect.
772 *
773 * Params:
774 * val = The new scheduling priority of this thread.
775 */
776 final @property void priority( int val )
777 in
778 {
779 assert(val >= PRIORITY_MIN);
780 assert(val <= PRIORITY_MAX);
781 }
782 do
783 {
784 version (Windows)
785 {
786 if ( !SetThreadPriority( m_hndl, val ) )
787 throw new ThreadException( "Unable to set thread priority" );
788 }
789 else version (Solaris)
790 {
791 // the pthread_setschedprio(3c) and pthread_setschedparam functions
792 // are broken for the default (TS / time sharing) scheduling class.
793 // instead, we use priocntl(2) which gives us the desired behavior.
794
795 // We hardcode the min and max priorities to the current value
796 // so this is a no-op for RT threads.
797 if (m_isRTClass)
798 return;
799
800 pcparms_t pcparm;
801
802 pcparm.pc_cid = PC_CLNULL;
803 if (priocntl(idtype_t.P_LWPID, P_MYID, PC_GETPARMS, &pcparm) == -1)
804 throw new ThreadException( "Unable to get scheduling class" );
805
806 pri_t* clparms = cast(pri_t*)&pcparm.pc_clparms;
807
808 // clparms is filled in by the PC_GETPARMS call, only necessary
809 // to adjust the element that contains the thread priority
810 clparms[1] = cast(pri_t) val;
811
812 if (priocntl(idtype_t.P_LWPID, P_MYID, PC_SETPARMS, &pcparm) == -1)
813 throw new ThreadException( "Unable to set scheduling class" );
814 }
815 else version (NetBSD)
816 {
817 fakePriority = val;
818 }
819 else version (Posix)
820 {
821 static if (__traits(compiles, core.sys.posix.pthread.pthread_setschedprio))
822 {
823 import core.sys.posix.pthread : pthread_setschedprio;
824
825 if (auto err = pthread_setschedprio(m_addr, val))
826 {
827 // ignore error if thread is not running => Bugzilla 8960
828 if (!atomicLoad(m_isRunning)) return;
829 throw new ThreadException("Unable to set thread priority");
830 }
831 }
832 else
833 {
834 // NOTE: pthread_setschedprio is not implemented on Darwin, FreeBSD, OpenBSD,
835 // or DragonFlyBSD, so use the more complicated get/set sequence below.
836 int policy;
837 sched_param param;
838
839 if (auto err = pthread_getschedparam(m_addr, &policy, &param))
840 {
841 // ignore error if thread is not running => Bugzilla 8960
842 if (!atomicLoad(m_isRunning)) return;
843 throw new ThreadException("Unable to set thread priority");
844 }
845 param.sched_priority = val;
846 if (auto err = pthread_setschedparam(m_addr, policy, &param))
847 {
848 // ignore error if thread is not running => Bugzilla 8960
849 if (!atomicLoad(m_isRunning)) return;
850 throw new ThreadException("Unable to set thread priority");
851 }
852 }
853 }
854 }
855
856
857 unittest
858 {
859 auto thr = Thread.getThis();
860 immutable prio = thr.priority;
861 scope (exit) thr.priority = prio;
862
863 assert(prio == PRIORITY_DEFAULT);
864 assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX);
865 thr.priority = PRIORITY_MIN;
866 assert(thr.priority == PRIORITY_MIN);
867 thr.priority = PRIORITY_MAX;
868 assert(thr.priority == PRIORITY_MAX);
869 }
870
871 unittest // Bugzilla 8960
872 {
873 import core.sync.semaphore;
874
875 auto thr = new Thread({});
876 thr.start();
877 Thread.sleep(1.msecs); // wait a little so the thread likely has finished
878 thr.priority = PRIORITY_MAX; // setting priority doesn't cause error
879 auto prio = thr.priority; // getting priority doesn't cause error
880 assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX);
881 }
882
883 /**
884 * Tests whether this thread is running.
885 *
886 * Returns:
887 * true if the thread is running, false if not.
888 */
889 override final @property bool isRunning() nothrow @nogc
890 {
891 if (!super.isRunning())
892 return false;
893
894 version (Windows)
895 {
896 uint ecode = 0;
897 GetExitCodeThread( m_hndl, &ecode );
898 return ecode == STILL_ACTIVE;
899 }
900 else version (Posix)
901 {
902 return atomicLoad(m_isRunning);
903 }
904 }
905
906
907 ///////////////////////////////////////////////////////////////////////////
908 // Actions on Calling Thread
909 ///////////////////////////////////////////////////////////////////////////
910
911
912 /**
913 * Suspends the calling thread for at least the supplied period. This may
914 * result in multiple OS calls if period is greater than the maximum sleep
915 * duration supported by the operating system.
916 *
917 * Params:
918 * val = The minimum duration the calling thread should be suspended.
919 *
920 * In:
921 * period must be non-negative.
922 *
923 * Example:
924 * ------------------------------------------------------------------------
925 *
926 * Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
927 * Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
928 *
929 * ------------------------------------------------------------------------
930 */
931 static void sleep( Duration val ) @nogc nothrow @trusted
932 in
933 {
934 assert( !val.isNegative );
935 }
936 do
937 {
938 version (Windows)
939 {
940 auto maxSleepMillis = dur!("msecs")( uint.max - 1 );
941
942 // avoid a non-zero time to be round down to 0
943 if ( val > dur!"msecs"( 0 ) && val < dur!"msecs"( 1 ) )
944 val = dur!"msecs"( 1 );
945
946 // NOTE: In instances where all other threads in the process have a
947 // lower priority than the current thread, the current thread
948 // will not yield with a sleep time of zero. However, unlike
949 // yield(), the user is not asking for a yield to occur but
950 // only for execution to suspend for the requested interval.
951 // Therefore, expected performance may not be met if a yield
952 // is forced upon the user.
953 while ( val > maxSleepMillis )
954 {
955 Sleep( cast(uint)
956 maxSleepMillis.total!"msecs" );
957 val -= maxSleepMillis;
958 }
959 Sleep( cast(uint) val.total!"msecs" );
960 }
961 else version (Posix)
962 {
963 timespec tin = void;
964 timespec tout = void;
965
966 val.split!("seconds", "nsecs")(tin.tv_sec, tin.tv_nsec);
967 if ( val.total!"seconds" > tin.tv_sec.max )
968 tin.tv_sec = tin.tv_sec.max;
969 while ( true )
970 {
971 if ( !nanosleep( &tin, &tout ) )
972 return;
973 if ( errno != EINTR )
974 assert(0, "Unable to sleep for the specified duration");
975 tin = tout;
976 }
977 }
978 }
979
980
981 /**
982 * Forces a context switch to occur away from the calling thread.
983 */
984 static void yield() @nogc nothrow
985 {
986 version (Windows)
987 SwitchToThread();
988 else version (Posix)
989 sched_yield();
990 }
991 }
992
993 private Thread toThread(return scope ThreadBase t) @trusted nothrow @nogc pure
994 {
995 return cast(Thread) cast(void*) t;
996 }
997
998 private extern(D) static void thread_yield() @nogc nothrow
999 {
1000 Thread.yield();
1001 }
1002
1003 ///
1004 unittest
1005 {
1006 class DerivedThread : Thread
1007 {
1008 this()
1009 {
1010 super(&run);
1011 }
1012
1013 private:
1014 void run()
1015 {
1016 // Derived thread running.
1017 }
1018 }
1019
1020 void threadFunc()
1021 {
1022 // Composed thread running.
1023 }
1024
1025 // create and start instances of each type
1026 auto derived = new DerivedThread().start();
1027 auto composed = new Thread(&threadFunc).start();
1028 new Thread({
1029 // Codes to run in the newly created thread.
1030 }).start();
1031 }
1032
1033 unittest
1034 {
1035 int x = 0;
1036
1037 new Thread(
1038 {
1039 x++;
1040 }).start().join();
1041 assert( x == 1 );
1042 }
1043
1044
1045 unittest
1046 {
1047 enum MSG = "Test message.";
1048 string caughtMsg;
1049
1050 try
1051 {
1052 new Thread(
1053 function()
1054 {
1055 throw new Exception( MSG );
1056 }).start().join();
1057 assert( false, "Expected rethrown exception." );
1058 }
1059 catch ( Throwable t )
1060 {
1061 assert( t.msg == MSG );
1062 }
1063 }
1064
1065
1066 unittest
1067 {
1068 // use >pageSize to avoid stack overflow (e.g. in an syscall)
1069 auto thr = new Thread(function{}, 4096 + 1).start();
1070 thr.join();
1071 }
1072
1073
1074 unittest
1075 {
1076 import core.memory : GC;
1077
1078 auto t1 = new Thread({
1079 foreach (_; 0 .. 20)
1080 ThreadBase.getAll;
1081 }).start;
1082 auto t2 = new Thread({
1083 foreach (_; 0 .. 20)
1084 GC.collect;
1085 }).start;
1086 t1.join();
1087 t2.join();
1088 }
1089
1090 unittest
1091 {
1092 import core.sync.semaphore;
1093 auto sem = new Semaphore();
1094
1095 auto t = new Thread(
1096 {
1097 sem.notify();
1098 Thread.sleep(100.msecs);
1099 }).start();
1100
1101 sem.wait(); // thread cannot be detached while being started
1102 thread_detachInstance(t);
1103 foreach (t2; Thread)
1104 assert(t !is t2);
1105 t.join();
1106 }
1107
1108 // https://issues.dlang.org/show_bug.cgi?id=22124
1109 unittest
1110 {
1111 Thread thread = new Thread({});
1112 auto fun(Thread t, int x)
1113 {
1114 t.__ctor({x = 3;});
1115 return t;
1116 }
1117 static assert(!__traits(compiles, () @nogc => fun(thread, 3) ));
1118 }
1119
1120 @nogc @safe nothrow
1121 unittest
1122 {
1123 Thread.sleep(1.msecs);
1124 }
1125
1126 ///////////////////////////////////////////////////////////////////////////////
1127 // GC Support Routines
1128 ///////////////////////////////////////////////////////////////////////////////
1129
1130 version (CoreDdoc)
1131 {
1132 /**
1133 * Instruct the thread module, when initialized, to use a different set of
1134 * signals besides SIGRTMIN and SIGRTMIN + 1 for suspension and resumption of threads.
1135 * This function should be called at most once, prior to thread_init().
1136 * This function is Posix-only.
1137 */
1138 extern (C) void thread_setGCSignals(int suspendSignalNo, int resumeSignalNo) nothrow @nogc
1139 {
1140 }
1141 }
1142 else version (Posix)
1143 {
1144 extern (C) void thread_setGCSignals(int suspendSignalNo, int resumeSignalNo) nothrow @nogc
1145 in
1146 {
1147 assert(suspendSignalNo != 0);
1148 assert(resumeSignalNo != 0);
1149 }
1150 out
1151 {
1152 assert(suspendSignalNumber != 0);
1153 assert(resumeSignalNumber != 0);
1154 }
1155 do
1156 {
1157 suspendSignalNumber = suspendSignalNo;
1158 resumeSignalNumber = resumeSignalNo;
1159 }
1160 }
1161
1162 version (Posix)
1163 {
1164 private __gshared int suspendSignalNumber;
1165 private __gshared int resumeSignalNumber;
1166 }
1167
1168 private extern (D) ThreadBase attachThread(ThreadBase _thisThread) @nogc nothrow
1169 {
1170 Thread thisThread = _thisThread.toThread();
1171
1172 StackContext* thisContext = &thisThread.m_main;
1173 assert( thisContext == thisThread.m_curr );
1174
1175 version (Windows)
1176 {
1177 thisThread.m_addr = GetCurrentThreadId();
1178 thisThread.m_hndl = GetCurrentThreadHandle();
1179 thisContext.bstack = getStackBottom();
1180 thisContext.tstack = thisContext.bstack;
1181 }
1182 else version (Posix)
1183 {
1184 thisThread.m_addr = pthread_self();
1185 thisContext.bstack = getStackBottom();
1186 thisContext.tstack = thisContext.bstack;
1187
1188 atomicStore!(MemoryOrder.raw)(thisThread.toThread.m_isRunning, true);
1189 }
1190 thisThread.m_isDaemon = true;
1191 thisThread.tlsRTdataInit();
1192 Thread.setThis( thisThread );
1193
1194 version (Darwin)
1195 {
1196 thisThread.m_tmach = pthread_mach_thread_np( thisThread.m_addr );
1197 assert( thisThread.m_tmach != thisThread.m_tmach.init );
1198 }
1199
1200 Thread.add( thisThread, false );
1201 Thread.add( thisContext );
1202 if ( Thread.sm_main !is null )
1203 multiThreadedFlag = true;
1204 return thisThread;
1205 }
1206
1207 /**
1208 * Registers the calling thread for use with the D Runtime. If this routine
1209 * is called for a thread which is already registered, no action is performed.
1210 *
1211 * NOTE: This routine does not run thread-local static constructors when called.
1212 * If full functionality as a D thread is desired, the following function
1213 * must be called after thread_attachThis:
1214 *
1215 * extern (C) void rt_moduleTlsCtor();
1216 *
1217 * See_Also:
1218 * $(REF thread_detachThis, core,thread,threadbase)
1219 */
1220 extern(C) Thread thread_attachThis()
1221 {
1222 return thread_attachThis_tpl!Thread();
1223 }
1224
1225
1226 version (Windows)
1227 {
1228 // NOTE: These calls are not safe on Posix systems that use signals to
1229 // perform garbage collection. The suspendHandler uses getThis()
1230 // to get the thread handle so getThis() must be a simple call.
1231 // Mutexes can't safely be acquired inside signal handlers, and
1232 // even if they could, the mutex needed (Thread.slock) is held by
1233 // thread_suspendAll(). So in short, these routines will remain
1234 // Windows-specific. If they are truly needed elsewhere, the
1235 // suspendHandler will need a way to call a version of getThis()
1236 // that only does the TLS lookup without the fancy fallback stuff.
1237
1238 /// ditto
1239 extern (C) Thread thread_attachByAddr( ThreadID addr )
1240 {
1241 return thread_attachByAddrB( addr, getThreadStackBottom( addr ) );
1242 }
1243
1244
1245 /// ditto
1246 extern (C) Thread thread_attachByAddrB( ThreadID addr, void* bstack )
1247 {
1248 GC.disable(); scope(exit) GC.enable();
1249
1250 if (auto t = thread_findByAddr(addr).toThread)
1251 return t;
1252
1253 Thread thisThread = new Thread();
1254 StackContext* thisContext = &thisThread.m_main;
1255 assert( thisContext == thisThread.m_curr );
1256
1257 thisThread.m_addr = addr;
1258 thisContext.bstack = bstack;
1259 thisContext.tstack = thisContext.bstack;
1260
1261 thisThread.m_isDaemon = true;
1262
1263 if ( addr == GetCurrentThreadId() )
1264 {
1265 thisThread.m_hndl = GetCurrentThreadHandle();
1266 thisThread.tlsRTdataInit();
1267 Thread.setThis( thisThread );
1268 }
1269 else
1270 {
1271 thisThread.m_hndl = OpenThreadHandle( addr );
1272 impersonate_thread(addr,
1273 {
1274 thisThread.tlsRTdataInit();
1275 Thread.setThis( thisThread );
1276 });
1277 }
1278
1279 Thread.add( thisThread, false );
1280 Thread.add( thisContext );
1281 if ( Thread.sm_main !is null )
1282 multiThreadedFlag = true;
1283 return thisThread;
1284 }
1285 }
1286
1287
1288 // Calls the given delegate, passing the current thread's stack pointer to it.
1289 package extern(D) void callWithStackShell(scope callWithStackShellDg fn) nothrow
1290 in (fn)
1291 {
1292 // The purpose of the 'shell' is to ensure all the registers get
1293 // put on the stack so they'll be scanned. We only need to push
1294 // the callee-save registers.
1295 void *sp = void;
1296 version (GNU)
1297 {
1298 // The generic solution below using a call to __builtin_unwind_init ()
1299 // followed by an assignment to sp has two issues:
1300 // 1) On some archs it stores a huge amount of FP and Vector state which
1301 // is not the subject of the scan - and, indeed might produce false
1302 // hits.
1303 // 2) Even on archs like X86, where there are no callee-saved FPRs/VRs there
1304 // tend to be 'holes' in the frame allocations (to deal with alignment) which
1305 // also will contain random data which could produce false positives.
1306 // This solution stores only the integer callee-saved registers.
1307 version (X86)
1308 {
1309 void*[3] regs = void;
1310 asm pure nothrow @nogc
1311 {
1312 "movl %%ebx, %0" : "=m" (regs[0]);
1313 "movl %%esi, %0" : "=m" (regs[1]);
1314 "movl %%edi, %0" : "=m" (regs[2]);
1315 }
1316 sp = cast(void*)&regs[0];
1317 }
1318 else version (X86_64)
1319 {
1320 void*[5] regs = void;
1321 asm pure nothrow @nogc
1322 {
1323 "movq %%rbx, %0" : "=m" (regs[0]);
1324 "movq %%r12, %0" : "=m" (regs[1]);
1325 "movq %%r13, %0" : "=m" (regs[2]);
1326 "movq %%r14, %0" : "=m" (regs[3]);
1327 "movq %%r15, %0" : "=m" (regs[4]);
1328 }
1329 sp = cast(void*)&regs[0];
1330 }
1331 else version (PPC)
1332 {
1333 void*[19] regs = void;
1334 version (Darwin)
1335 enum regname = "r";
1336 else
1337 enum regname = "";
1338 static foreach (i; 0 .. regs.length)
1339 {{
1340 enum int j = 13 + i; // source register
1341 asm pure nothrow @nogc
1342 {
1343 "stw "~regname~j.stringof~", %0" : "=m" (regs[i]);
1344 }
1345 }}
1346 sp = cast(void*)&regs[0];
1347 }
1348 else version (PPC64)
1349 {
1350 void*[19] regs = void;
1351 version (Darwin)
1352 enum regname = "r";
1353 else
1354 enum regname = "";
1355 static foreach (i; 0 .. regs.length)
1356 {{
1357 enum int j = 13 + i; // source register
1358 asm pure nothrow @nogc
1359 {
1360 "std "~regname~j.stringof~", %0" : "=m" (regs[i]);
1361 }
1362 }}
1363 sp = cast(void*)&regs[0];
1364 }
1365 else version (AArch64)
1366 {
1367 // Callee-save registers, x19-x28 according to AAPCS64, section
1368 // 5.1.1. Include x29 fp because it optionally can be a callee
1369 // saved reg
1370 size_t[11] regs = void;
1371 // store the registers in pairs
1372 asm pure nothrow @nogc
1373 {
1374 "stp x19, x20, %0" : "=m" (regs[ 0]), "=m" (regs[1]);
1375 "stp x21, x22, %0" : "=m" (regs[ 2]), "=m" (regs[3]);
1376 "stp x23, x24, %0" : "=m" (regs[ 4]), "=m" (regs[5]);
1377 "stp x25, x26, %0" : "=m" (regs[ 6]), "=m" (regs[7]);
1378 "stp x27, x28, %0" : "=m" (regs[ 8]), "=m" (regs[9]);
1379 "str x29, %0" : "=m" (regs[10]);
1380 "mov %0, sp" : "=r" (sp);
1381 }
1382 }
1383 else version (ARM)
1384 {
1385 // Callee-save registers, according to AAPCS, section 5.1.1.
1386 // arm and thumb2 instructions
1387 size_t[8] regs = void;
1388 asm pure nothrow @nogc
1389 {
1390 "stm %0, {r4-r11}" : : "r" (regs.ptr) : "memory";
1391 "mov %0, sp" : "=r" (sp);
1392 }
1393 }
1394 else
1395 {
1396 __builtin_unwind_init();
1397 sp = &sp;
1398 }
1399 }
1400 else version (AsmX86_Posix)
1401 {
1402 size_t[3] regs = void;
1403 asm pure nothrow @nogc
1404 {
1405 mov [regs + 0 * 4], EBX;
1406 mov [regs + 1 * 4], ESI;
1407 mov [regs + 2 * 4], EDI;
1408
1409 mov sp[EBP], ESP;
1410 }
1411 }
1412 else version (AsmX86_Windows)
1413 {
1414 size_t[3] regs = void;
1415 asm pure nothrow @nogc
1416 {
1417 mov [regs + 0 * 4], EBX;
1418 mov [regs + 1 * 4], ESI;
1419 mov [regs + 2 * 4], EDI;
1420
1421 mov sp[EBP], ESP;
1422 }
1423 }
1424 else version (AsmX86_64_Posix)
1425 {
1426 size_t[5] regs = void;
1427 asm pure nothrow @nogc
1428 {
1429 mov [regs + 0 * 8], RBX;
1430 mov [regs + 1 * 8], R12;
1431 mov [regs + 2 * 8], R13;
1432 mov [regs + 3 * 8], R14;
1433 mov [regs + 4 * 8], R15;
1434
1435 mov sp[RBP], RSP;
1436 }
1437 }
1438 else version (AsmX86_64_Windows)
1439 {
1440 size_t[7] regs = void;
1441 asm pure nothrow @nogc
1442 {
1443 mov [regs + 0 * 8], RBX;
1444 mov [regs + 1 * 8], RSI;
1445 mov [regs + 2 * 8], RDI;
1446 mov [regs + 3 * 8], R12;
1447 mov [regs + 4 * 8], R13;
1448 mov [regs + 5 * 8], R14;
1449 mov [regs + 6 * 8], R15;
1450
1451 mov sp[RBP], RSP;
1452 }
1453 }
1454 else
1455 {
1456 static assert(false, "Architecture not supported.");
1457 }
1458
1459 fn(sp);
1460 }
1461
1462 version (Windows)
1463 private extern (D) void scanWindowsOnly(scope ScanAllThreadsTypeFn scan, ThreadBase _t) nothrow
1464 {
1465 auto t = _t.toThread;
1466
1467 scan( ScanType.stack, t.m_reg.ptr, t.m_reg.ptr + t.m_reg.length );
1468 }
1469
1470
1471 /**
1472 * Returns the process ID of the calling process, which is guaranteed to be
1473 * unique on the system. This call is always successful.
1474 *
1475 * Example:
1476 * ---
1477 * writefln("Current process id: %s", getpid());
1478 * ---
1479 */
1480 version (Posix)
1481 {
1482 alias getpid = imported!"core.sys.posix.unistd".getpid;
1483 }
1484 else version (Windows)
1485 {
1486 alias getpid = imported!"core.sys.windows.winbase".GetCurrentProcessId;
1487 }
1488
1489 extern (C) @nogc nothrow
1490 {
1491 version (CRuntime_Glibc) version = PThread_Getattr_NP;
1492 version (CRuntime_Bionic) version = PThread_Getattr_NP;
1493 version (CRuntime_Musl) version = PThread_Getattr_NP;
1494 version (CRuntime_UClibc) version = PThread_Getattr_NP;
1495
1496 version (FreeBSD) version = PThread_Attr_Get_NP;
1497 version (NetBSD) version = PThread_Attr_Get_NP;
1498 version (DragonFlyBSD) version = PThread_Attr_Get_NP;
1499
1500 version (PThread_Getattr_NP) int pthread_getattr_np(pthread_t thread, pthread_attr_t* attr);
1501 version (PThread_Attr_Get_NP) int pthread_attr_get_np(pthread_t thread, pthread_attr_t* attr);
1502 version (Solaris) int thr_stksegment(stack_t* stk);
1503 version (OpenBSD) int pthread_stackseg_np(pthread_t thread, stack_t* sinfo);
1504 }
1505
1506
1507 private extern(D) void* getStackTop() nothrow @nogc
1508 {
1509 version (D_InlineAsm_X86)
1510 asm pure nothrow @nogc { naked; mov EAX, ESP; ret; }
1511 else version (D_InlineAsm_X86_64)
1512 asm pure nothrow @nogc { naked; mov RAX, RSP; ret; }
1513 else version (GNU)
1514 return __builtin_frame_address(0);
1515 else
1516 static assert(false, "Architecture not supported.");
1517 }
1518
1519
1520 private extern(D) void* getStackBottom() nothrow @nogc
1521 {
1522 version (Windows)
1523 {
1524 version (D_InlineAsm_X86)
1525 asm pure nothrow @nogc { naked; mov EAX, FS:4; ret; }
1526 else version (D_InlineAsm_X86_64)
1527 asm pure nothrow @nogc
1528 { naked;
1529 mov RAX, 8;
1530 mov RAX, GS:[RAX];
1531 ret;
1532 }
1533 else version (GNU_InlineAsm)
1534 {
1535 void *bottom;
1536
1537 version (X86)
1538 asm pure nothrow @nogc { "movl %%fs:4, %0;" : "=r" (bottom); }
1539 else version (X86_64)
1540 asm pure nothrow @nogc { "movq %%gs:8, %0;" : "=r" (bottom); }
1541 else
1542 static assert(false, "Architecture not supported.");
1543
1544 return bottom;
1545 }
1546 else
1547 static assert(false, "Architecture not supported.");
1548 }
1549 else version (Darwin)
1550 {
1551 import core.sys.darwin.pthread : pthread_get_stackaddr_np;
1552 return pthread_get_stackaddr_np(pthread_self());
1553 }
1554 else version (PThread_Getattr_NP)
1555 {
1556 pthread_attr_t attr;
1557 void* addr; size_t size;
1558
1559 pthread_attr_init(&attr);
1560 pthread_getattr_np(pthread_self(), &attr);
1561 pthread_attr_getstack(&attr, &addr, &size);
1562 pthread_attr_destroy(&attr);
1563 static if (isStackGrowingDown)
1564 addr += size;
1565 return addr;
1566 }
1567 else version (PThread_Attr_Get_NP)
1568 {
1569 pthread_attr_t attr;
1570 void* addr; size_t size;
1571
1572 pthread_attr_init(&attr);
1573 pthread_attr_get_np(pthread_self(), &attr);
1574 pthread_attr_getstack(&attr, &addr, &size);
1575 pthread_attr_destroy(&attr);
1576 static if (isStackGrowingDown)
1577 addr += size;
1578 return addr;
1579 }
1580 else version (OpenBSD)
1581 {
1582 stack_t stk;
1583
1584 pthread_stackseg_np(pthread_self(), &stk);
1585 return stk.ss_sp;
1586 }
1587 else version (Solaris)
1588 {
1589 stack_t stk;
1590
1591 thr_stksegment(&stk);
1592 return stk.ss_sp;
1593 }
1594 else
1595 static assert(false, "Platform not supported.");
1596 }
1597
1598 /**
1599 * Suspend the specified thread and load stack and register information for
1600 * use by thread_scanAll. If the supplied thread is the calling thread,
1601 * stack and register information will be loaded but the thread will not
1602 * be suspended. If the suspend operation fails and the thread is not
1603 * running then it will be removed from the global thread list, otherwise
1604 * an exception will be thrown.
1605 *
1606 * Params:
1607 * t = The thread to suspend.
1608 *
1609 * Throws:
1610 * ThreadError if the suspend operation fails for a running thread.
1611 * Returns:
1612 * Whether the thread is now suspended (true) or terminated (false).
1613 */
1614 private extern (D) bool suspend( Thread t ) nothrow @nogc
1615 {
1616 if (!t.isRunning)
1617 {
1618 Thread.remove(t);
1619 return false;
1620 }
1621
1622 version (Windows)
1623 {
1624 if ( t.m_addr != GetCurrentThreadId() && SuspendThread( t.m_hndl ) == 0xFFFFFFFF )
1625 {
1626 if ( !t.isRunning )
1627 {
1628 Thread.remove( t );
1629 return false;
1630 }
1631 onThreadError( "Unable to suspend thread" );
1632 }
1633
1634 CONTEXT context = void;
1635 context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
1636
1637 if ( !GetThreadContext( t.m_hndl, &context ) )
1638 onThreadError( "Unable to load thread context" );
1639 version (X86)
1640 {
1641 if ( !t.m_lock )
1642 t.m_curr.tstack = cast(void*) context.Esp;
1643 // eax,ebx,ecx,edx,edi,esi,ebp,esp
1644 t.m_reg[0] = context.Eax;
1645 t.m_reg[1] = context.Ebx;
1646 t.m_reg[2] = context.Ecx;
1647 t.m_reg[3] = context.Edx;
1648 t.m_reg[4] = context.Edi;
1649 t.m_reg[5] = context.Esi;
1650 t.m_reg[6] = context.Ebp;
1651 t.m_reg[7] = context.Esp;
1652 }
1653 else version (X86_64)
1654 {
1655 if ( !t.m_lock )
1656 t.m_curr.tstack = cast(void*) context.Rsp;
1657 // rax,rbx,rcx,rdx,rdi,rsi,rbp,rsp
1658 t.m_reg[0] = context.Rax;
1659 t.m_reg[1] = context.Rbx;
1660 t.m_reg[2] = context.Rcx;
1661 t.m_reg[3] = context.Rdx;
1662 t.m_reg[4] = context.Rdi;
1663 t.m_reg[5] = context.Rsi;
1664 t.m_reg[6] = context.Rbp;
1665 t.m_reg[7] = context.Rsp;
1666 // r8,r9,r10,r11,r12,r13,r14,r15
1667 t.m_reg[8] = context.R8;
1668 t.m_reg[9] = context.R9;
1669 t.m_reg[10] = context.R10;
1670 t.m_reg[11] = context.R11;
1671 t.m_reg[12] = context.R12;
1672 t.m_reg[13] = context.R13;
1673 t.m_reg[14] = context.R14;
1674 t.m_reg[15] = context.R15;
1675 }
1676 else
1677 {
1678 static assert(false, "Architecture not supported." );
1679 }
1680 }
1681 else version (Darwin)
1682 {
1683 if ( t.m_addr != pthread_self() && thread_suspend( t.m_tmach ) != KERN_SUCCESS )
1684 {
1685 if ( !t.isRunning )
1686 {
1687 Thread.remove( t );
1688 return false;
1689 }
1690 onThreadError( "Unable to suspend thread" );
1691 }
1692
1693 version (X86)
1694 {
1695 x86_thread_state32_t state = void;
1696 mach_msg_type_number_t count = x86_THREAD_STATE32_COUNT;
1697
1698 if ( thread_get_state( t.m_tmach, x86_THREAD_STATE32, &state, &count ) != KERN_SUCCESS )
1699 onThreadError( "Unable to load thread state" );
1700 if ( !t.m_lock )
1701 t.m_curr.tstack = cast(void*) state.esp;
1702 // eax,ebx,ecx,edx,edi,esi,ebp,esp
1703 t.m_reg[0] = state.eax;
1704 t.m_reg[1] = state.ebx;
1705 t.m_reg[2] = state.ecx;
1706 t.m_reg[3] = state.edx;
1707 t.m_reg[4] = state.edi;
1708 t.m_reg[5] = state.esi;
1709 t.m_reg[6] = state.ebp;
1710 t.m_reg[7] = state.esp;
1711 }
1712 else version (X86_64)
1713 {
1714 x86_thread_state64_t state = void;
1715 mach_msg_type_number_t count = x86_THREAD_STATE64_COUNT;
1716
1717 if ( thread_get_state( t.m_tmach, x86_THREAD_STATE64, &state, &count ) != KERN_SUCCESS )
1718 onThreadError( "Unable to load thread state" );
1719 if ( !t.m_lock )
1720 t.m_curr.tstack = cast(void*) state.rsp;
1721 // rax,rbx,rcx,rdx,rdi,rsi,rbp,rsp
1722 t.m_reg[0] = state.rax;
1723 t.m_reg[1] = state.rbx;
1724 t.m_reg[2] = state.rcx;
1725 t.m_reg[3] = state.rdx;
1726 t.m_reg[4] = state.rdi;
1727 t.m_reg[5] = state.rsi;
1728 t.m_reg[6] = state.rbp;
1729 t.m_reg[7] = state.rsp;
1730 // r8,r9,r10,r11,r12,r13,r14,r15
1731 t.m_reg[8] = state.r8;
1732 t.m_reg[9] = state.r9;
1733 t.m_reg[10] = state.r10;
1734 t.m_reg[11] = state.r11;
1735 t.m_reg[12] = state.r12;
1736 t.m_reg[13] = state.r13;
1737 t.m_reg[14] = state.r14;
1738 t.m_reg[15] = state.r15;
1739 }
1740 else version (AArch64)
1741 {
1742 arm_thread_state64_t state = void;
1743 mach_msg_type_number_t count = ARM_THREAD_STATE64_COUNT;
1744
1745 if (thread_get_state(t.m_tmach, ARM_THREAD_STATE64, &state, &count) != KERN_SUCCESS)
1746 onThreadError("Unable to load thread state");
1747 // TODO: ThreadException here recurses forever! Does it
1748 //still using onThreadError?
1749 //printf("state count %d (expect %d)\n", count ,ARM_THREAD_STATE64_COUNT);
1750 if (!t.m_lock)
1751 t.m_curr.tstack = cast(void*) state.sp;
1752
1753 t.m_reg[0..29] = state.x; // x0-x28
1754 t.m_reg[29] = state.fp; // x29
1755 t.m_reg[30] = state.lr; // x30
1756 t.m_reg[31] = state.sp; // x31
1757 t.m_reg[32] = state.pc;
1758 }
1759 else version (ARM)
1760 {
1761 arm_thread_state32_t state = void;
1762 mach_msg_type_number_t count = ARM_THREAD_STATE32_COUNT;
1763
1764 // Thought this would be ARM_THREAD_STATE32, but that fails.
1765 // Mystery
1766 if (thread_get_state(t.m_tmach, ARM_THREAD_STATE, &state, &count) != KERN_SUCCESS)
1767 onThreadError("Unable to load thread state");
1768 // TODO: in past, ThreadException here recurses forever! Does it
1769 //still using onThreadError?
1770 //printf("state count %d (expect %d)\n", count ,ARM_THREAD_STATE32_COUNT);
1771 if (!t.m_lock)
1772 t.m_curr.tstack = cast(void*) state.sp;
1773
1774 t.m_reg[0..13] = state.r; // r0 - r13
1775 t.m_reg[13] = state.sp;
1776 t.m_reg[14] = state.lr;
1777 t.m_reg[15] = state.pc;
1778 }
1779 else version (PPC)
1780 {
1781 ppc_thread_state_t state = void;
1782 mach_msg_type_number_t count = PPC_THREAD_STATE_COUNT;
1783
1784 if (thread_get_state(t.m_tmach, PPC_THREAD_STATE, &state, &count) != KERN_SUCCESS)
1785 onThreadError("Unable to load thread state");
1786 if (!t.m_lock)
1787 t.m_curr.tstack = cast(void*) state.r[1];
1788 t.m_reg[] = state.r[];
1789 }
1790 else version (PPC64)
1791 {
1792 ppc_thread_state64_t state = void;
1793 mach_msg_type_number_t count = PPC_THREAD_STATE64_COUNT;
1794
1795 if (thread_get_state(t.m_tmach, PPC_THREAD_STATE64, &state, &count) != KERN_SUCCESS)
1796 onThreadError("Unable to load thread state");
1797 if (!t.m_lock)
1798 t.m_curr.tstack = cast(void*) state.r[1];
1799 t.m_reg[] = state.r[];
1800 }
1801 else
1802 {
1803 static assert(false, "Architecture not supported." );
1804 }
1805 }
1806 else version (Posix)
1807 {
1808 if ( t.m_addr != pthread_self() )
1809 {
1810 if ( pthread_kill( t.m_addr, suspendSignalNumber ) != 0 )
1811 {
1812 if ( !t.isRunning )
1813 {
1814 Thread.remove( t );
1815 return false;
1816 }
1817 onThreadError( "Unable to suspend thread" );
1818 }
1819 }
1820 else if ( !t.m_lock )
1821 {
1822 t.m_curr.tstack = getStackTop();
1823 }
1824 }
1825 return true;
1826 }
1827
1828 /**
1829 * Runs the necessary operations required before stopping the world.
1830 */
1831 extern (C) void thread_preStopTheWorld() nothrow {
1832 Thread.slock.lock_nothrow();
1833 }
1834
1835 /**
1836 * Suspend all threads but the calling thread for "stop the world" garbage
1837 * collection runs. This function may be called multiple times, and must
1838 * be followed by a matching number of calls to thread_resumeAll before
1839 * processing is resumed.
1840 *
1841 * Throws:
1842 * ThreadError if the suspend operation fails for a running thread.
1843 */
1844 extern (C) void thread_suspendAll() nothrow
1845 {
1846 // NOTE: We've got an odd chicken & egg problem here, because while the GC
1847 // is required to call thread_init before calling any other thread
1848 // routines, thread_init may allocate memory which could in turn
1849 // trigger a collection. Thus, thread_suspendAll, thread_scanAll,
1850 // and thread_resumeAll must be callable before thread_init
1851 // completes, with the assumption that no other GC memory has yet
1852 // been allocated by the system, and thus there is no risk of losing
1853 // data if the global thread list is empty. The check of
1854 // Thread.sm_tbeg below is done to ensure thread_init has completed,
1855 // and therefore that calling Thread.getThis will not result in an
1856 // error. For the short time when Thread.sm_tbeg is null, there is
1857 // no reason not to simply call the multithreaded code below, with
1858 // the expectation that the foreach loop will never be entered.
1859 if ( !multiThreadedFlag && Thread.sm_tbeg )
1860 {
1861 if ( ++suspendDepth == 1 )
1862 suspend( Thread.getThis() );
1863
1864 return;
1865 }
1866
1867 thread_preStopTheWorld();
1868 {
1869 if ( ++suspendDepth > 1 )
1870 return;
1871
1872 size_t cnt;
1873 bool suspendedSelf;
1874 Thread t = ThreadBase.sm_tbeg.toThread;
1875 while (t)
1876 {
1877 auto tn = t.next.toThread;
1878 if (suspend(t))
1879 {
1880 if (t is ThreadBase.getThis())
1881 suspendedSelf = true;
1882 ++cnt;
1883 }
1884 t = tn;
1885 }
1886
1887 version (Darwin)
1888 {}
1889 else version (Posix)
1890 {
1891 // Subtract own thread if we called suspend() on ourselves.
1892 // For example, suspendedSelf would be false if the current
1893 // thread ran thread_detachThis().
1894 assert(cnt >= 1);
1895 if (suspendedSelf)
1896 --cnt;
1897 // wait for semaphore notifications
1898 for (; cnt; --cnt)
1899 {
1900 while (sem_wait(&suspendCount) != 0)
1901 {
1902 if (errno != EINTR)
1903 onThreadError("Unable to wait for semaphore");
1904 errno = 0;
1905 }
1906 }
1907 }
1908 }
1909 }
1910
1911 /**
1912 * Resume the specified thread and unload stack and register information.
1913 * If the supplied thread is the calling thread, stack and register
1914 * information will be unloaded but the thread will not be resumed. If
1915 * the resume operation fails and the thread is not running then it will
1916 * be removed from the global thread list, otherwise an exception will be
1917 * thrown.
1918 *
1919 * Params:
1920 * t = The thread to resume.
1921 *
1922 * Throws:
1923 * ThreadError if the resume fails for a running thread.
1924 */
1925 private extern (D) void resume(ThreadBase _t) nothrow @nogc
1926 {
1927 Thread t = _t.toThread;
1928
1929 version (Windows)
1930 {
1931 if ( t.m_addr != GetCurrentThreadId() && ResumeThread( t.m_hndl ) == 0xFFFFFFFF )
1932 {
1933 if ( !t.isRunning )
1934 {
1935 Thread.remove( t );
1936 return;
1937 }
1938 onThreadError( "Unable to resume thread" );
1939 }
1940
1941 if ( !t.m_lock )
1942 t.m_curr.tstack = t.m_curr.bstack;
1943 t.m_reg[0 .. $] = 0;
1944 }
1945 else version (Darwin)
1946 {
1947 if ( t.m_addr != pthread_self() && thread_resume( t.m_tmach ) != KERN_SUCCESS )
1948 {
1949 if ( !t.isRunning )
1950 {
1951 Thread.remove( t );
1952 return;
1953 }
1954 onThreadError( "Unable to resume thread" );
1955 }
1956
1957 if ( !t.m_lock )
1958 t.m_curr.tstack = t.m_curr.bstack;
1959 t.m_reg[0 .. $] = 0;
1960 }
1961 else version (Posix)
1962 {
1963 if ( t.m_addr != pthread_self() )
1964 {
1965 if ( pthread_kill( t.m_addr, resumeSignalNumber ) != 0 )
1966 {
1967 if ( !t.isRunning )
1968 {
1969 Thread.remove( t );
1970 return;
1971 }
1972 onThreadError( "Unable to resume thread" );
1973 }
1974 }
1975 else if ( !t.m_lock )
1976 {
1977 t.m_curr.tstack = t.m_curr.bstack;
1978 }
1979 }
1980 else
1981 static assert(false, "Platform not supported.");
1982 }
1983
1984
1985 /**
1986 * Initializes the thread module. This function must be called by the
1987 * garbage collector on startup and before any other thread routines
1988 * are called.
1989 */
1990 extern (C) void thread_init() @nogc nothrow
1991 {
1992 // NOTE: If thread_init itself performs any allocations then the thread
1993 // routines reserved for garbage collector use may be called while
1994 // thread_init is being processed. However, since no memory should
1995 // exist to be scanned at this point, it is sufficient for these
1996 // functions to detect the condition and return immediately.
1997
1998 initLowlevelThreads();
1999 Thread.initLocks();
2000
2001 version (Darwin)
2002 {
2003 // thread id different in forked child process
2004 static extern(C) void initChildAfterFork()
2005 {
2006 auto thisThread = Thread.getThis();
2007 if (!thisThread)
2008 {
2009 // It is possible that runtime was not properly initialized in the current process or thread -
2010 // it may happen after `fork` call when using a dynamically loaded shared library written in D from a multithreaded non-D program.
2011 // In such case getThis will return null.
2012 return;
2013 }
2014 thisThread.m_addr = pthread_self();
2015 assert( thisThread.m_addr != thisThread.m_addr.init );
2016 thisThread.m_tmach = pthread_mach_thread_np( thisThread.m_addr );
2017 assert( thisThread.m_tmach != thisThread.m_tmach.init );
2018 }
2019 pthread_atfork(null, null, &initChildAfterFork);
2020 }
2021 else version (Posix)
2022 {
2023 version (OpenBSD)
2024 {
2025 // OpenBSD does not support SIGRTMIN or SIGRTMAX
2026 // Use SIGUSR1 for SIGRTMIN, SIGUSR2 for SIGRTMIN + 1
2027 // And use 32 for SIGRTMAX (32 is the max signal number on OpenBSD)
2028 enum SIGRTMIN = SIGUSR1;
2029 enum SIGRTMAX = 32;
2030 }
2031 else
2032 {
2033 import core.sys.posix.signal : SIGRTMAX, SIGRTMIN;
2034 }
2035
2036 if ( suspendSignalNumber == 0 )
2037 {
2038 suspendSignalNumber = SIGRTMIN;
2039 }
2040
2041 if ( resumeSignalNumber == 0 )
2042 {
2043 resumeSignalNumber = SIGRTMIN + 1;
2044 assert(resumeSignalNumber <= SIGRTMAX);
2045 }
2046 int status;
2047 sigaction_t suspend = void;
2048 sigaction_t resume = void;
2049
2050 // This is a quick way to zero-initialize the structs without using
2051 // memset or creating a link dependency on their static initializer.
2052 (cast(byte*) &suspend)[0 .. sigaction_t.sizeof] = 0;
2053 (cast(byte*) &resume)[0 .. sigaction_t.sizeof] = 0;
2054
2055 // NOTE: SA_RESTART indicates that system calls should restart if they
2056 // are interrupted by a signal, but this is not available on all
2057 // Posix systems, even those that support multithreading.
2058 static if (__traits(compiles, core.sys.posix.signal.SA_RESTART))
2059 {
2060 import core.sys.posix.signal : SA_RESTART;
2061
2062 suspend.sa_flags = SA_RESTART;
2063 }
2064
2065 suspend.sa_handler = &thread_suspendHandler;
2066 // NOTE: We want to ignore all signals while in this handler, so fill
2067 // sa_mask to indicate this.
2068 status = sigfillset( &suspend.sa_mask );
2069 assert( status == 0 );
2070
2071 // NOTE: Since resumeSignalNumber should only be issued for threads within the
2072 // suspend handler, we don't want this signal to trigger a
2073 // restart.
2074 resume.sa_flags = 0;
2075 resume.sa_handler = &thread_resumeHandler;
2076 // NOTE: We want to ignore all signals while in this handler, so fill
2077 // sa_mask to indicate this.
2078 status = sigfillset( &resume.sa_mask );
2079 assert( status == 0 );
2080
2081 status = sigaction( suspendSignalNumber, &suspend, null );
2082 assert( status == 0 );
2083
2084 status = sigaction( resumeSignalNumber, &resume, null );
2085 assert( status == 0 );
2086
2087 status = sem_init( &suspendCount, 0, 0 );
2088 assert( status == 0 );
2089 }
2090 _mainThreadStore[] = cast(void[]) __traits(initSymbol, Thread)[];
2091 Thread.sm_main = attachThread((cast(Thread)_mainThreadStore.ptr).__ctor());
2092 }
2093
2094 private alias MainThreadStore = void[__traits(classInstanceSize, Thread)];
2095 package __gshared align(__traits(classInstanceAlignment, Thread)) MainThreadStore _mainThreadStore;
2096
2097 /**
2098 * Terminates the thread module. No other thread routine may be called
2099 * afterwards.
2100 */
2101 extern (C) void thread_term() @nogc nothrow
2102 {
2103 thread_term_tpl!(Thread)(_mainThreadStore);
2104 }
2105
2106
2107 ///////////////////////////////////////////////////////////////////////////////
2108 // Thread Entry Point and Signal Handlers
2109 ///////////////////////////////////////////////////////////////////////////////
2110
2111
2112 version (Windows)
2113 {
2114 private
2115 {
2116 //
2117 // Entry point for Windows threads
2118 //
2119 extern (Windows) uint thread_entryPoint( void* arg ) nothrow
2120 {
2121 Thread obj = cast(Thread) arg;
2122 assert( obj );
2123
2124 obj.initDataStorage();
2125
2126 Thread.registerThis(obj);
2127
2128 scope (exit)
2129 {
2130 Thread.remove(obj);
2131 obj.destroyDataStorage();
2132 }
2133 Thread.add(&obj.m_main);
2134
2135 // NOTE: No GC allocations may occur until the stack pointers have
2136 // been set and Thread.getThis returns a valid reference to
2137 // this thread object (this latter condition is not strictly
2138 // necessary on Windows but it should be followed for the
2139 // sake of consistency).
2140
2141 // TODO: Consider putting an auto exception object here (using
2142 // alloca) forOutOfMemoryError plus something to track
2143 // whether an exception is in-flight?
2144
2145 void append( Throwable t )
2146 {
2147 obj.m_unhandled = Throwable.chainTogether(obj.m_unhandled, t);
2148 }
2149
2150 version (D_InlineAsm_X86)
2151 {
2152 asm nothrow @nogc { fninit; }
2153 }
2154
2155 try
2156 {
2157 rt_moduleTlsCtor();
2158 try
2159 {
2160 obj.run();
2161 }
2162 catch ( Throwable t )
2163 {
2164 append( t );
2165 }
2166 rt_moduleTlsDtor();
2167 }
2168 catch ( Throwable t )
2169 {
2170 append( t );
2171 }
2172 return 0;
2173 }
2174
2175
2176 HANDLE GetCurrentThreadHandle() nothrow @nogc
2177 {
2178 const uint DUPLICATE_SAME_ACCESS = 0x00000002;
2179
2180 HANDLE curr = GetCurrentThread(),
2181 proc = GetCurrentProcess(),
2182 hndl;
2183
2184 DuplicateHandle( proc, curr, proc, &hndl, 0, TRUE, DUPLICATE_SAME_ACCESS );
2185 return hndl;
2186 }
2187 }
2188 }
2189 else version (Posix)
2190 {
2191 private
2192 {
2193 //
2194 // Entry point for POSIX threads
2195 //
2196 extern (C) void* thread_entryPoint( void* arg ) nothrow
2197 {
2198 version (Shared)
2199 {
2200 Thread obj = cast(Thread)(cast(void**)arg)[0];
2201 auto loadedLibraries = (cast(void**)arg)[1];
2202 .free(arg);
2203 }
2204 else
2205 {
2206 Thread obj = cast(Thread)arg;
2207 }
2208 assert( obj );
2209
2210 // loadedLibraries need to be inherited from parent thread
2211 // before initilizing GC for TLS (rt_tlsgc_init)
2212 version (Shared)
2213 {
2214 externDFunc!("rt.sections_elf_shared.inheritLoadedLibraries",
2215 void function(void*) @nogc nothrow)(loadedLibraries);
2216 }
2217
2218 obj.initDataStorage();
2219
2220 atomicStore!(MemoryOrder.raw)(obj.m_isRunning, true);
2221
2222 Thread.registerThis(obj); // can only receive signals from here on
2223
2224 scope (exit)
2225 {
2226 Thread.remove(obj);
2227 atomicStore!(MemoryOrder.raw)(obj.m_isRunning, false);
2228 obj.destroyDataStorage();
2229 }
2230 Thread.add(&obj.m_main);
2231
2232 static extern (C) void thread_cleanupHandler( void* arg ) nothrow @nogc
2233 {
2234 Thread obj = cast(Thread) arg;
2235 assert( obj );
2236
2237 // NOTE: If the thread terminated abnormally, just set it as
2238 // not running and let thread_suspendAll remove it from
2239 // the thread list. This is safer and is consistent
2240 // with the Windows thread code.
2241 atomicStore!(MemoryOrder.raw)(obj.m_isRunning,false);
2242 }
2243
2244 // NOTE: Using void to skip the initialization here relies on
2245 // knowledge of how pthread_cleanup is implemented. It may
2246 // not be appropriate for all platforms. However, it does
2247 // avoid the need to link the pthread module. If any
2248 // implementation actually requires default initialization
2249 // then pthread_cleanup should be restructured to maintain
2250 // the current lack of a link dependency.
2251 static if (__traits(compiles, core.sys.posix.pthread.pthread_cleanup))
2252 {
2253 import core.sys.posix.pthread : pthread_cleanup;
2254
2255 pthread_cleanup cleanup = void;
2256 cleanup.push( &thread_cleanupHandler, cast(void*) obj );
2257 }
2258 else static if (__traits(compiles, core.sys.posix.pthread.pthread_cleanup_push))
2259 {
2260 import core.sys.posix.pthread : pthread_cleanup_push;
2261
2262 pthread_cleanup_push(&thread_cleanupHandler, cast(void*) obj);
2263 }
2264 else
2265 {
2266 static assert( false, "Platform not supported." );
2267 }
2268
2269 // NOTE: No GC allocations may occur until the stack pointers have
2270 // been set and Thread.getThis returns a valid reference to
2271 // this thread object (this latter condition is not strictly
2272 // necessary on Windows but it should be followed for the
2273 // sake of consistency).
2274
2275 // TODO: Consider putting an auto exception object here (using
2276 // alloca) forOutOfMemoryError plus something to track
2277 // whether an exception is in-flight?
2278
2279 void append( Throwable t )
2280 {
2281 obj.m_unhandled = Throwable.chainTogether(obj.m_unhandled, t);
2282 }
2283 try
2284 {
2285 rt_moduleTlsCtor();
2286 try
2287 {
2288 obj.run();
2289 }
2290 catch ( Throwable t )
2291 {
2292 append( t );
2293 }
2294 rt_moduleTlsDtor();
2295 version (Shared)
2296 {
2297 externDFunc!("rt.sections_elf_shared.cleanupLoadedLibraries",
2298 void function() @nogc nothrow)();
2299 }
2300 }
2301 catch ( Throwable t )
2302 {
2303 append( t );
2304 }
2305
2306 // NOTE: Normal cleanup is handled by scope(exit).
2307
2308 static if (__traits(compiles, core.sys.posix.pthread.pthread_cleanup))
2309 {
2310 cleanup.pop( 0 );
2311 }
2312 else static if (__traits(compiles, core.sys.posix.pthread.pthread_cleanup_push))
2313 {
2314 import core.sys.posix.pthread : pthread_cleanup_pop;
2315
2316 pthread_cleanup_pop( 0 );
2317 }
2318
2319 return null;
2320 }
2321
2322
2323 //
2324 // Used to track the number of suspended threads
2325 //
2326 __gshared sem_t suspendCount;
2327
2328
2329 extern (C) bool thread_preSuspend( void* sp ) nothrow {
2330 // NOTE: Since registers are being pushed and popped from the
2331 // stack, any other stack data used by this function should
2332 // be gone before the stack cleanup code is called below.
2333 Thread obj = Thread.getThis();
2334 if (obj is null)
2335 {
2336 return false;
2337 }
2338
2339 if ( !obj.m_lock )
2340 {
2341 obj.m_curr.tstack = sp;
2342 }
2343
2344 return true;
2345 }
2346
2347 extern (C) bool thread_postSuspend() nothrow {
2348 Thread obj = Thread.getThis();
2349 if (obj is null)
2350 {
2351 return false;
2352 }
2353
2354 if ( !obj.m_lock )
2355 {
2356 obj.m_curr.tstack = obj.m_curr.bstack;
2357 }
2358
2359 return true;
2360 }
2361
2362 extern (C) void thread_suspendHandler( int sig ) nothrow
2363 in
2364 {
2365 assert( sig == suspendSignalNumber );
2366 }
2367 do
2368 {
2369 void op(void* sp) nothrow
2370 {
2371 bool supported = thread_preSuspend(getStackTop());
2372 assert(supported, "Tried to suspend a detached thread!");
2373
2374 scope(exit)
2375 {
2376 supported = thread_postSuspend();
2377 assert(supported, "Tried to suspend a detached thread!");
2378 }
2379
2380 sigset_t sigres = void;
2381 int status;
2382
2383 status = sigfillset( &sigres );
2384 assert( status == 0 );
2385
2386 status = sigdelset( &sigres, resumeSignalNumber );
2387 assert( status == 0 );
2388
2389 status = sem_post( &suspendCount );
2390 assert( status == 0 );
2391
2392 sigsuspend( &sigres );
2393 }
2394 callWithStackShell(&op);
2395 }
2396
2397
2398 extern (C) void thread_resumeHandler( int sig ) nothrow
2399 in
2400 {
2401 assert( sig == resumeSignalNumber );
2402 }
2403 do
2404 {
2405
2406 }
2407 }
2408 }
2409 else
2410 {
2411 // NOTE: This is the only place threading versions are checked. If a new
2412 // version is added, the module code will need to be searched for
2413 // places where version-specific code may be required. This can be
2414 // easily accomlished by searching for 'Windows' or 'Posix'.
2415 static assert( false, "Unknown threading implementation." );
2416 }
2417
2418 //
2419 // exposed by compiler runtime
2420 //
2421 extern (C) void rt_moduleTlsCtor();
2422 extern (C) void rt_moduleTlsDtor();
2423
2424
2425 // regression test for Issue 13416
2426 version (FreeBSD) unittest
2427 {
2428 static void loop()
2429 {
2430 pthread_attr_t attr;
2431 pthread_attr_init(&attr);
2432 auto thr = pthread_self();
2433 foreach (i; 0 .. 50)
2434 pthread_attr_get_np(thr, &attr);
2435 pthread_attr_destroy(&attr);
2436 }
2437
2438 auto thr = new Thread(&loop).start();
2439 foreach (i; 0 .. 50)
2440 {
2441 thread_suspendAll();
2442 thread_resumeAll();
2443 }
2444 thr.join();
2445 }
2446
2447 version (DragonFlyBSD) unittest
2448 {
2449 static void loop()
2450 {
2451 pthread_attr_t attr;
2452 pthread_attr_init(&attr);
2453 auto thr = pthread_self();
2454 foreach (i; 0 .. 50)
2455 pthread_attr_get_np(thr, &attr);
2456 pthread_attr_destroy(&attr);
2457 }
2458
2459 auto thr = new Thread(&loop).start();
2460 foreach (i; 0 .. 50)
2461 {
2462 thread_suspendAll();
2463 thread_resumeAll();
2464 }
2465 thr.join();
2466 }
2467
2468
2469 ///////////////////////////////////////////////////////////////////////////////
2470 // lowlovel threading support
2471 ///////////////////////////////////////////////////////////////////////////////
2472
2473 private
2474 {
2475 version (Windows):
2476 // If the runtime is dynamically loaded as a DLL, there is a problem with
2477 // threads still running when the DLL is supposed to be unloaded:
2478 //
2479 // - with the VC runtime starting with VS2015 (i.e. using the Universal CRT)
2480 // a thread created with _beginthreadex increments the DLL reference count
2481 // and decrements it when done, so that the DLL is no longer unloaded unless
2482 // all the threads have terminated. With the DLL reference count held up
2483 // by a thread that is only stopped by a signal from a static destructor or
2484 // the termination of the runtime will cause the DLL to never be unloaded.
2485 //
2486 // - with the DigitalMars runtime and VC runtime up to VS2013, the thread
2487 // continues to run, but crashes once the DLL is unloaded from memory as
2488 // the code memory is no longer accessible. Stopping the threads is not possible
2489 // from within the runtime termination as it is invoked from
2490 // DllMain(DLL_PROCESS_DETACH) holding a lock that prevents threads from
2491 // terminating.
2492 //
2493 // Solution: start a watchdog thread that keeps the DLL reference count above 0 and
2494 // checks it periodically. If it is equal to 1 (plus the number of started threads), no
2495 // external references to the DLL exist anymore, threads can be stopped
2496 // and runtime termination and DLL unload can be invoked via FreeLibraryAndExitThread.
2497 // Note: runtime termination is then performed by a different thread than at startup.
2498 //
2499 // Note: if the DLL is never unloaded, process termination kills all threads
2500 // and signals their handles before unconditionally calling DllMain(DLL_PROCESS_DETACH).
2501
2502 import core.sys.windows.dll : dll_getRefCount;
2503 import core.sys.windows.winbase : FreeLibraryAndExitThread, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleHandleExW;
2504 import core.sys.windows.windef : HMODULE;
2505
2506 version (CRuntime_Microsoft)
2507 extern(C) extern __gshared ubyte msvcUsesUCRT; // from rt/msvc.d
2508
2509 /// set during termination of a DLL on Windows, i.e. while executing DllMain(DLL_PROCESS_DETACH)
2510 public __gshared bool thread_DLLProcessDetaching;
2511
2512 __gshared HMODULE ll_dllModule;
2513 __gshared ThreadID ll_dllMonitorThread;
2514
2515 int ll_countLowLevelThreadsWithDLLUnloadCallback() nothrow
2516 {
2517 lowlevelLock.lock_nothrow();
2518 scope(exit) lowlevelLock.unlock_nothrow();
2519
2520 int cnt = 0;
2521 foreach (i; 0 .. ll_nThreads)
2522 if (ll_pThreads[i].cbDllUnload)
2523 cnt++;
2524 return cnt;
2525 }
2526
2527 bool ll_dllHasExternalReferences() nothrow
2528 {
2529 int internalReferences = msvcUsesUCRT ? 1 + ll_countLowLevelThreadsWithDLLUnloadCallback() : 1;
2530 int refcnt = dll_getRefCount(ll_dllModule);
2531 return refcnt > internalReferences;
2532 }
2533
2534 private void monitorDLLRefCnt() nothrow
2535 {
2536 // this thread keeps the DLL alive until all external references are gone
2537 while (ll_dllHasExternalReferences())
2538 {
2539 Thread.sleep(100.msecs);
2540 }
2541
2542 // the current thread will be terminated below
2543 ll_removeThread(GetCurrentThreadId());
2544
2545 for (;;)
2546 {
2547 ThreadID tid;
2548 void delegate() nothrow cbDllUnload;
2549 {
2550 lowlevelLock.lock_nothrow();
2551 scope(exit) lowlevelLock.unlock_nothrow();
2552
2553 foreach (i; 0 .. ll_nThreads)
2554 if (ll_pThreads[i].cbDllUnload)
2555 {
2556 cbDllUnload = ll_pThreads[i].cbDllUnload;
2557 tid = ll_pThreads[0].tid;
2558 }
2559 }
2560 if (!cbDllUnload)
2561 break;
2562 cbDllUnload();
2563 assert(!findLowLevelThread(tid));
2564 }
2565
2566 FreeLibraryAndExitThread(ll_dllModule, 0);
2567 }
2568
2569 int ll_getDLLRefCount() nothrow @nogc
2570 {
2571 if (!ll_dllModule &&
2572 !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
2573 cast(const(wchar)*) &ll_getDLLRefCount, &ll_dllModule))
2574 return -1;
2575 return dll_getRefCount(ll_dllModule);
2576 }
2577
2578 bool ll_startDLLUnloadThread() nothrow @nogc
2579 {
2580 int refcnt = ll_getDLLRefCount();
2581 if (refcnt < 0)
2582 return false; // not a dynamically loaded DLL
2583
2584 if (ll_dllMonitorThread !is ThreadID.init)
2585 return true;
2586
2587 // if a thread is created from a DLL, the MS runtime (starting with VC2015) increments the DLL reference count
2588 // to avoid the DLL being unloaded while the thread is still running. Mimick this behavior here for all
2589 // runtimes not doing this
2590 bool needRef = !msvcUsesUCRT;
2591
2592 if (needRef)
2593 {
2594 HMODULE hmod;
2595 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, cast(const(wchar)*) &ll_getDLLRefCount, &hmod);
2596 }
2597
2598 ll_dllMonitorThread = createLowLevelThread(() { monitorDLLRefCnt(); });
2599 return ll_dllMonitorThread != ThreadID.init;
2600 }
2601 }
2602
2603 /**
2604 * Create a thread not under control of the runtime, i.e. TLS module constructors are
2605 * not run and the GC does not suspend it during a collection.
2606 *
2607 * Params:
2608 * dg = delegate to execute in the created thread.
2609 * stacksize = size of the stack of the created thread. The default of 0 will select the
2610 * platform-specific default size.
2611 * cbDllUnload = Windows only: if running in a dynamically loaded DLL, this delegate will be called
2612 * if the DLL is supposed to be unloaded, but the thread is still running.
2613 * The thread must be terminated via `joinLowLevelThread` by the callback.
2614 *
2615 * Returns: the platform specific thread ID of the new thread. If an error occurs, `ThreadID.init`
2616 * is returned.
2617 */
2618 ThreadID createLowLevelThread(void delegate() nothrow dg, uint stacksize = 0,
2619 void delegate() nothrow cbDllUnload = null) nothrow @nogc
2620 {
2621 void delegate() nothrow* context = cast(void delegate() nothrow*)malloc(dg.sizeof);
2622 *context = dg;
2623
2624 ThreadID tid;
2625 version (Windows)
2626 {
2627 // the thread won't start until after the DLL is unloaded
2628 if (thread_DLLProcessDetaching)
2629 return ThreadID.init;
2630
2631 static extern (Windows) uint thread_lowlevelEntry(void* ctx) nothrow
2632 {
2633 auto dg = *cast(void delegate() nothrow*)ctx;
2634 free(ctx);
2635
2636 dg();
2637 ll_removeThread(GetCurrentThreadId());
2638 return 0;
2639 }
2640
2641 // see Thread.start() for why thread is created in suspended state
2642 HANDLE hThread = cast(HANDLE) _beginthreadex(null, stacksize, &thread_lowlevelEntry,
2643 context, CREATE_SUSPENDED, &tid);
2644 if (!hThread)
2645 return ThreadID.init;
2646 }
2647
2648 lowlevelLock.lock_nothrow();
2649 scope(exit) lowlevelLock.unlock_nothrow();
2650
2651 ll_nThreads++;
2652 ll_pThreads = cast(ll_ThreadData*)realloc(ll_pThreads, ll_ThreadData.sizeof * ll_nThreads);
2653
2654 version (Windows)
2655 {
2656 ll_pThreads[ll_nThreads - 1].tid = tid;
2657 ll_pThreads[ll_nThreads - 1].cbDllUnload = cbDllUnload;
2658 if (ResumeThread(hThread) == -1)
2659 onThreadError("Error resuming thread");
2660 CloseHandle(hThread);
2661
2662 if (cbDllUnload)
2663 ll_startDLLUnloadThread();
2664 }
2665 else version (Posix)
2666 {
2667 static extern (C) void* thread_lowlevelEntry(void* ctx) nothrow
2668 {
2669 auto dg = *cast(void delegate() nothrow*)ctx;
2670 free(ctx);
2671
2672 dg();
2673 ll_removeThread(pthread_self());
2674 return null;
2675 }
2676
2677 size_t stksz = adjustStackSize(stacksize);
2678
2679 pthread_attr_t attr;
2680
2681 int rc;
2682 if ((rc = pthread_attr_init(&attr)) != 0)
2683 return ThreadID.init;
2684 if (stksz && (rc = pthread_attr_setstacksize(&attr, stksz)) != 0)
2685 return ThreadID.init;
2686 if ((rc = pthread_create(&tid, &attr, &thread_lowlevelEntry, context)) != 0)
2687 return ThreadID.init;
2688 if ((rc = pthread_attr_destroy(&attr)) != 0)
2689 return ThreadID.init;
2690
2691 ll_pThreads[ll_nThreads - 1].tid = tid;
2692 }
2693 return tid;
2694 }
2695
2696 /**
2697 * Wait for a thread created with `createLowLevelThread` to terminate.
2698 *
2699 * Note: In a Windows DLL, if this function is called via DllMain with
2700 * argument DLL_PROCESS_DETACH, the thread is terminated forcefully
2701 * without proper cleanup as a deadlock would happen otherwise.
2702 *
2703 * Params:
2704 * tid = the thread ID returned by `createLowLevelThread`.
2705 */
2706 void joinLowLevelThread(ThreadID tid) nothrow @nogc
2707 {
2708 version (Windows)
2709 {
2710 HANDLE handle = OpenThreadHandle(tid);
2711 if (!handle)
2712 return;
2713
2714 if (thread_DLLProcessDetaching)
2715 {
2716 // When being called from DllMain/DLL_DETACH_PROCESS, threads cannot stop
2717 // due to the loader lock being held by the current thread.
2718 // On the other hand, the thread must not continue to run as it will crash
2719 // if the DLL is unloaded. The best guess is to terminate it immediately.
2720 TerminateThread(handle, 1);
2721 WaitForSingleObject(handle, 10); // give it some time to terminate, but don't wait indefinitely
2722 }
2723 else
2724 WaitForSingleObject(handle, INFINITE);
2725 CloseHandle(handle);
2726 }
2727 else version (Posix)
2728 {
2729 if (pthread_join(tid, null) != 0)
2730 onThreadError("Unable to join thread");
2731 }
2732 }
2733
2734 nothrow @nogc unittest
2735 {
2736 struct TaskWithContect
2737 {
2738 shared int n = 0;
2739 void run() nothrow
2740 {
2741 n.atomicOp!"+="(1);
2742 }
2743 }
2744 TaskWithContect task;
2745
2746 ThreadID[8] tids;
2747 for (int i = 0; i < tids.length; i++)
2748 {
2749 tids[i] = createLowLevelThread(&task.run);
2750 assert(tids[i] != ThreadID.init);
2751 }
2752
2753 for (int i = 0; i < tids.length; i++)
2754 joinLowLevelThread(tids[i]);
2755
2756 assert(task.n == tids.length);
2757 }
2758
2759 version (Posix)
2760 private size_t adjustStackSize(size_t sz) nothrow @nogc
2761 {
2762 if (sz == 0)
2763 return 0;
2764
2765 // stack size must be at least PTHREAD_STACK_MIN for most platforms.
2766 if (PTHREAD_STACK_MIN > sz)
2767 sz = PTHREAD_STACK_MIN;
2768
2769 version (CRuntime_Glibc)
2770 {
2771 // On glibc, TLS uses the top of the stack, so add its size to the requested size
2772 sz += externDFunc!("rt.sections_elf_shared.sizeOfTLS",
2773 size_t function() @nogc nothrow)();
2774 }
2775
2776 // stack size must be a multiple of pageSize
2777 sz = ((sz + pageSize - 1) & ~(pageSize - 1));
2778
2779 return sz;
2780 }