1 /**
2  * The threadbase module provides OS-independent code
3  * for thread storage 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 strand.threadbase;
14 
15 import strand.context;
16 import strand.types;
17 import core.time;
18 import core.sync.mutex;
19 import core.stdc.stdlib : free, realloc;
20 
21 private
22 {
23     // interface to rt.tlsgc
24     pragma(mangle, "_D2rt5tlsgc4initFNbNiZPv")
25     extern(D) void* function() nothrow @nogc rt_tlsgc_init;
26 
27     pragma(mangle, "_D2rt5tlsgc7destroyFNbNiPvZv")
28     extern(D) void function(void*) nothrow @nogc rt_tlsgc_destroy;
29 
30     alias ScanDg = void delegate(void* pstart, void* pend) nothrow;
31 
32     pragma(mangle, "_D2rt5tlsgc4scanFNbPvMDFNbQhQjZvZv")
33     extern(D) void function(void*, scope ScanDg) nothrow rt_tlsgc_scan;
34 
35     pragma(mangle, "_D2rt5tlsgc14processGCMarksFNbPvMDFNbQhZiZv")
36     extern(D) void function(void*, scope IsMarkedDg) nothrow rt_tlsgc_processGCMarks;
37 }
38 
39 
40 ///////////////////////////////////////////////////////////////////////////////
41 // Thread and Fiber Exceptions
42 ///////////////////////////////////////////////////////////////////////////////
43 
44 
45 /**
46  * Base class for thread exceptions.
47  */
48 class ThreadException : Exception
49 {
50     @nogc @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
51     {
52         super(msg, file, line, next);
53     }
54 
55     @nogc @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
56     {
57         super(msg, file, line, next);
58     }
59 }
60 
61 
62 /**
63 * Base class for thread errors to be used for function inside GC when allocations are unavailable.
64 */
65 class ThreadError : Error
66 {
67     @nogc @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
68     {
69         super(msg, file, line, next);
70     }
71 
72     @nogc @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
73     {
74         super(msg, file, line, next);
75     }
76 }
77 
78 private
79 {
80     // Handling unaligned mutexes are not supported on all platforms, so we must
81     // ensure that the address of all shared data are appropriately aligned.
82     enum mutexAlign = __traits(classInstanceAlignment, Mutex);
83     enum mutexClassInstanceSize = __traits(classInstanceSize, Mutex);
84 
85     pragma(mangle, "_D6strand8osthread11swapContextFNbNiPvZQd")
86     extern(D) void* function(void*) nothrow @nogc swapContext;
87 
88     pragma(mangle, "_D6strand8osthread14getStackBottomFNbNiZPv")
89     extern(D) void* function() nothrow @nogc getStackBottom;
90 
91     pragma(mangle, "_D6strand8osthread11getStackTopFNbNiZPv")
92     extern(D) void* function() nothrow @nogc getStackTop;
93 }
94 
95 
96 ///////////////////////////////////////////////////////////////////////////////
97 // Thread
98 ///////////////////////////////////////////////////////////////////////////////
99 
100 
101 class ThreadBase
102 {
103     ///////////////////////////////////////////////////////////////////////////
104     // Initialization
105     ///////////////////////////////////////////////////////////////////////////
106 
107     this(void function() fn, size_t sz = 0) @safe pure nothrow @nogc
108     in(fn)
109     {
110         this(sz);
111         m_call = fn;
112     }
113 
114     this(void delegate() dg, size_t sz = 0) @trusted pure nothrow @nogc
115     in( cast(const void delegate()) dg)
116     {
117         this(sz);
118         m_call = dg;
119     }
120 
121     /**
122      * Cleans up any remaining resources used by this object.
123      */
124     package bool destructBeforeDtor() nothrow @nogc
125     {
126         destroyDataStorageIfAvail();
127 
128         bool no_context = m_addr == m_addr.init;
129         bool not_registered = !next && !prev && (sm_tbeg !is this);
130 
131         return (no_context || not_registered);
132     }
133 
134     package void tlsGCdataInit() nothrow @nogc
135     {
136         m_tlsgcdata = rt_tlsgc_init();
137     }
138 
139     package void initDataStorage() nothrow
140     {
141         assert(m_curr is &m_main);
142 
143         m_main.bstack = getStackBottom();
144         m_main.tstack = m_main.bstack;
145         tlsGCdataInit();
146     }
147 
148     package void destroyDataStorage() nothrow @nogc
149     {
150         rt_tlsgc_destroy(m_tlsgcdata);
151         m_tlsgcdata = null;
152     }
153 
154     package void destroyDataStorageIfAvail() nothrow @nogc
155     {
156         if (m_tlsgcdata)
157             destroyDataStorage();
158     }
159 
160 
161     ///////////////////////////////////////////////////////////////////////////
162     // General Actions
163     ///////////////////////////////////////////////////////////////////////////
164 
165 
166     /**
167      * Waits for this thread to complete.  If the thread terminated as the
168      * result of an unhandled exception, this exception will be rethrown.
169      *
170      * Params:
171      *  rethrow = Rethrow any unhandled exception which may have caused this
172      *            thread to terminate.
173      *
174      * Throws:
175      *  ThreadException if the operation fails.
176      *  Any exception not handled by the joined thread.
177      *
178      * Returns:
179      *  Any exception not handled by this thread if rethrow = false, null
180      *  otherwise.
181      */
182     abstract Throwable join(bool rethrow = true);
183 
184 
185     ///////////////////////////////////////////////////////////////////////////
186     // General Properties
187     ///////////////////////////////////////////////////////////////////////////
188 
189 
190     /**
191      * Gets the OS identifier for this thread.
192      *
193      * Returns:
194      *  If the thread hasn't been started yet, returns $(LREF ThreadID)$(D.init).
195      *  Otherwise, returns the result of $(D GetCurrentThreadId) on Windows,
196      *  and $(D pthread_self) on POSIX.
197      *
198      *  The value is unique for the current process.
199      */
200     final @property ThreadID id() @safe @nogc
201     {
202         synchronized(this)
203         {
204             return m_addr;
205         }
206     }
207 
208 
209     /**
210      * Gets the user-readable label for this thread.
211      *
212      * Returns:
213      *  The name of this thread.
214      */
215     final @property string name() @safe @nogc
216     {
217         synchronized(this)
218         {
219             return m_name;
220         }
221     }
222 
223 
224     /**
225      * Sets the user-readable label for this thread.
226      *
227      * Params:
228      *  val = The new name of this thread.
229      */
230     final @property void name(string val) @safe @nogc
231     {
232         synchronized(this)
233         {
234             m_name = val;
235         }
236     }
237 
238 
239     /**
240      * Gets the daemon status for this thread.  While the runtime will wait for
241      * all normal threads to complete before tearing down the process, daemon
242      * threads are effectively ignored and thus will not prevent the process
243      * from terminating.  In effect, daemon threads will be terminated
244      * automatically by the OS when the process exits.
245      *
246      * Returns:
247      *  true if this is a daemon thread.
248      */
249     final @property bool isDaemon() @safe @nogc
250     {
251         synchronized(this)
252         {
253             return m_isDaemon;
254         }
255     }
256 
257 
258     /**
259      * Sets the daemon status for this thread.  While the runtime will wait for
260      * all normal threads to complete before tearing down the process, daemon
261      * threads are effectively ignored and thus will not prevent the process
262      * from terminating.  In effect, daemon threads will be terminated
263      * automatically by the OS when the process exits.
264      *
265      * Params:
266      *  val = The new daemon status for this thread.
267      */
268     final @property void isDaemon(bool val) @safe @nogc
269     {
270         synchronized(this)
271         {
272             m_isDaemon = val;
273         }
274     }
275 
276     /**
277      * Tests whether this thread is the main thread, i.e. the thread
278      * that initialized the runtime
279      *
280      * Returns:
281      *  true if the thread is the main thread
282      */
283     final @property bool isMainThread() nothrow @nogc
284     {
285         return this is sm_main;
286     }
287 
288     /**
289      * Tests whether this thread is running.
290      *
291      * Returns:
292      *  true if the thread is running, false if not.
293      */
294     @property bool isRunning() nothrow @nogc
295     {
296         if (m_addr == m_addr.init)
297             return false;
298 
299         return true;
300     }
301 
302 
303     ///////////////////////////////////////////////////////////////////////////
304     // Thread Accessors
305     ///////////////////////////////////////////////////////////////////////////
306 
307     /**
308      * Provides a reference to the calling thread.
309      *
310      * Returns:
311      *  The thread object representing the calling thread.  The result of
312      *  deleting this object is undefined.  If the current thread is not
313      *  attached to the runtime, a null reference is returned.
314      */
315     static ThreadBase getThis() @safe nothrow @nogc
316     {
317         // NOTE: This function may not be called until thread_init has
318         //       completed.  See thread_suspendAll for more information
319         //       on why this might occur.
320         return sm_this;
321     }
322 
323 
324     /**
325      * Provides a list of all threads currently being tracked by the system.
326      * Note that threads in the returned array might no longer run (see
327      * $(D ThreadBase.)$(LREF isRunning)).
328      *
329      * Returns:
330      *  An array containing references to all threads currently being
331      *  tracked by the system.  The result of deleting any contained
332      *  objects is undefined.
333      */
334     static ThreadBase[] getAll()
335     {
336         static void resize(ref ThreadBase[] buf, size_t nlen)
337         {
338             buf.length = nlen;
339         }
340         return getAllImpl!resize();
341     }
342 
343 
344     /**
345      * Operates on all threads currently being tracked by the system.  The
346      * result of deleting any Thread object is undefined.
347      * Note that threads passed to the callback might no longer run (see
348      * $(D ThreadBase.)$(LREF isRunning)).
349      *
350      * Params:
351      *  dg = The supplied code as a delegate.
352      *
353      * Returns:
354      *  Zero if all elemented are visited, nonzero if not.
355      */
356     static int opApply(scope int delegate(ref ThreadBase) dg)
357     {
358         static void resize(ref ThreadBase[] buf, size_t nlen)
359         {
360             import core.exception: onOutOfMemoryError;
361 
362             auto newBuf = cast(ThreadBase*)realloc(buf.ptr, nlen * size_t.sizeof);
363             if (newBuf is null) onOutOfMemoryError();
364             buf = newBuf[0 .. nlen];
365         }
366         auto buf = getAllImpl!resize;
367         scope(exit) if (buf.ptr) free(buf.ptr);
368 
369         foreach (t; buf)
370         {
371             if (auto res = dg(t))
372                 return res;
373         }
374         return 0;
375     }
376 
377     private static ThreadBase[] getAllImpl(alias resize)()
378     {
379         import core.atomic;
380 
381         ThreadBase[] buf;
382         while (true)
383         {
384             immutable len = atomicLoad!(MemoryOrder.raw)(*cast(shared)&sm_tlen);
385             resize(buf, len);
386             assert(buf.length == len);
387             synchronized (slock)
388             {
389                 if (len == sm_tlen)
390                 {
391                     size_t pos;
392                     for (ThreadBase t = sm_tbeg; t; t = t.next)
393                         buf[pos++] = t;
394                     return buf;
395                 }
396             }
397         }
398     }
399 
400     ///////////////////////////////////////////////////////////////////////////
401     // Actions on Calling Thread
402     ///////////////////////////////////////////////////////////////////////////
403 
404     /**
405      * Forces a context switch to occur away from the calling thread.
406      */
407     private static void yield() @nogc nothrow
408     {
409         thread_yield();
410     }
411 
412     ///////////////////////////////////////////////////////////////////////////
413     // Stuff That Should Go Away
414     ///////////////////////////////////////////////////////////////////////////
415 
416 
417     //
418     // Initializes a thread object which has no associated executable function.
419     // This is used for the main thread initialized in thread_init().
420     //
421     package this(size_t sz = 0) @safe pure nothrow @nogc
422     {
423         m_sz = sz;
424         m_curr = &m_main;
425     }
426 
427     //
428     // Thread entry point.  Invokes the function or delegate passed on
429     // construction (if any).
430     //
431     package final void run()
432     {
433         m_call();
434     }
435 
436 package:
437 
438     //
439     // Local storage
440     //
441     static ThreadBase       sm_this;
442 
443 
444     //
445     // Main process thread
446     //
447     __gshared ThreadBase    sm_main;
448 
449 
450     //
451     // Standard thread data
452     //
453     ThreadID            m_addr;
454     Callable            m_call;
455     string              m_name;
456     size_t              m_sz;
457     bool                m_isDaemon;
458     bool                m_isInCriticalRegion;
459     Throwable           m_unhandled;
460 
461     ///////////////////////////////////////////////////////////////////////////
462     // Storage of Active Thread
463     ///////////////////////////////////////////////////////////////////////////
464 
465 
466     //
467     // Sets a thread-local reference to the current thread object.
468     //
469     package static void setThis(ThreadBase t) nothrow @nogc
470     {
471         sm_this = t;
472     }
473 
474 package(strand):
475 
476     StackContext        m_main;
477     StackContext*       m_curr;
478     bool                m_lock;
479     private void*       m_tlsgcdata;
480 
481     ///////////////////////////////////////////////////////////////////////////
482     // Thread Context and GC Scanning Support
483     ///////////////////////////////////////////////////////////////////////////
484 
485 
486     final void pushContext(StackContext* c) nothrow @nogc
487     in
488     {
489         assert(!c.within);
490     }
491     do
492     {
493         m_curr.ehContext = swapContext(c.ehContext);
494         c.within = m_curr;
495         m_curr = c;
496     }
497 
498 
499     final void popContext() nothrow @nogc
500     in
501     {
502         assert(m_curr && m_curr.within);
503     }
504     do
505     {
506         StackContext* c = m_curr;
507         m_curr = c.within;
508         c.ehContext = swapContext(m_curr.ehContext);
509         c.within = null;
510     }
511 
512     private final StackContext* topContext() nothrow @nogc
513     in(m_curr)
514     {
515         return m_curr;
516     }
517 
518 
519 package(strand):
520     ///////////////////////////////////////////////////////////////////////////
521     // GC Scanning Support
522     ///////////////////////////////////////////////////////////////////////////
523 
524 
525     // NOTE: The GC scanning process works like so:
526     //
527     //          1. Suspend all threads.
528     //          2. Scan the stacks of all suspended threads for roots.
529     //          3. Resume all threads.
530     //
531     //       Step 1 and 3 require a list of all threads in the system, while
532     //       step 2 requires a list of all thread stacks (each represented by
533     //       a Context struct).  Traditionally, there was one stack per thread
534     //       and the Context structs were not necessary.  However, Fibers have
535     //       changed things so that each thread has its own 'main' stack plus
536     //       an arbitrary number of nested stacks (normally referenced via
537     //       m_curr).  Also, there may be 'free-floating' stacks in the system,
538     //       which are Fibers that are not currently executing on any specific
539     //       thread but are still being processed and still contain valid
540     //       roots.
541     //
542     //       To support all of this, the Context struct has been created to
543     //       represent a stack range, and a global list of Context structs has
544     //       been added to enable scanning of these stack ranges.  The lifetime
545     //       (and presence in the Context list) of a thread's 'main' stack will
546     //       be equivalent to the thread's lifetime.  So the Ccontext will be
547     //       added to the list on thread entry, and removed from the list on
548     //       thread exit (which is essentially the same as the presence of a
549     //       Thread object in its own global list).  The lifetime of a Fiber's
550     //       context, however, will be tied to the lifetime of the Fiber object
551     //       itself, and Fibers are expected to add/remove their Context struct
552     //       on construction/deletion.
553 
554 
555     //
556     // All use of the global thread lists/array should synchronize on this lock.
557     //
558     // Careful as the GC acquires this lock after the GC lock to suspend all
559     // threads any GC usage with slock held can result in a deadlock through
560     // lock order inversion.
561     @property static Mutex slock() nothrow @nogc
562     {
563         return cast(Mutex)_slock.ptr;
564     }
565 
566     @property static Mutex criticalRegionLock() nothrow @nogc
567     {
568         return cast(Mutex)_criticalRegionLock.ptr;
569     }
570 
571     __gshared align(mutexAlign) void[mutexClassInstanceSize] _slock;
572     __gshared align(mutexAlign) void[mutexClassInstanceSize] _criticalRegionLock;
573 
574     static void initLocks() @nogc nothrow
575     {
576         import core.lifetime : emplace;
577         emplace!Mutex(_slock[]);
578         emplace!Mutex(_criticalRegionLock[]);
579     }
580 
581     static void termLocks() @nogc nothrow
582     {
583         (cast(Mutex)_slock.ptr).__dtor();
584         (cast(Mutex)_criticalRegionLock.ptr).__dtor();
585     }
586 
587     __gshared StackContext*  sm_cbeg;
588 
589     __gshared ThreadBase    sm_tbeg;
590     __gshared size_t        sm_tlen;
591 
592     // can't use core.internal.util.array in public code
593     __gshared ThreadBase* pAboutToStart;
594     __gshared size_t      nAboutToStart;
595 
596     //
597     // Used for ordering threads in the global thread list.
598     //
599     ThreadBase          prev;
600     ThreadBase          next;
601 
602 
603     ///////////////////////////////////////////////////////////////////////////
604     // Global Context List Operations
605     ///////////////////////////////////////////////////////////////////////////
606 
607 
608     //
609     // Add a context to the global context list.
610     //
611     static void add(StackContext* c) nothrow @nogc
612     in
613     {
614         assert(c);
615         assert(!c.next && !c.prev);
616     }
617     do
618     {
619         slock.lock_nothrow();
620         scope(exit) slock.unlock_nothrow();
621         assert(!suspendDepth); // must be 0 b/c it's only set with slock held
622 
623         if (sm_cbeg)
624         {
625             c.next = sm_cbeg;
626             sm_cbeg.prev = c;
627         }
628         sm_cbeg = c;
629     }
630 
631     //
632     // Remove a context from the global context list.
633     //
634     // This assumes slock being acquired. This isn't done here to
635     // avoid double locking when called from remove(Thread)
636     static void remove(StackContext* c) nothrow @nogc
637     in
638     {
639         assert(c);
640         assert(c.next || c.prev);
641     }
642     do
643     {
644         if (c.prev)
645             c.prev.next = c.next;
646         if (c.next)
647             c.next.prev = c.prev;
648         if (sm_cbeg == c)
649             sm_cbeg = c.next;
650         // NOTE: Don't null out c.next or c.prev because opApply currently
651         //       follows c.next after removing a node.  This could be easily
652         //       addressed by simply returning the next node from this
653         //       function, however, a context should never be re-added to the
654         //       list anyway and having next and prev be non-null is a good way
655         //       to ensure that.
656     }
657 
658 
659     ///////////////////////////////////////////////////////////////////////////
660     // Global Thread List Operations
661     ///////////////////////////////////////////////////////////////////////////
662 
663 
664     //
665     // Add a thread to the global thread list.
666     //
667     static void add(ThreadBase t, bool rmAboutToStart = true) nothrow @nogc
668     in
669     {
670         assert(t);
671         assert(!t.next && !t.prev);
672     }
673     do
674     {
675         slock.lock_nothrow();
676         scope(exit) slock.unlock_nothrow();
677         assert(t.isRunning); // check this with slock to ensure pthread_create already returned
678         assert(!suspendDepth); // must be 0 b/c it's only set with slock held
679 
680         if (rmAboutToStart)
681         {
682             size_t idx = -1;
683             foreach (i, thr; pAboutToStart[0 .. nAboutToStart])
684             {
685                 if (thr is t)
686                 {
687                     idx = i;
688                     break;
689                 }
690             }
691             assert(idx != -1);
692             import core.stdc.string : memmove;
693             memmove(pAboutToStart + idx, pAboutToStart + idx + 1, size_t.sizeof * (nAboutToStart - idx - 1));
694             pAboutToStart =
695                 cast(ThreadBase*)realloc(pAboutToStart, size_t.sizeof * --nAboutToStart);
696         }
697 
698         if (sm_tbeg)
699         {
700             t.next = sm_tbeg;
701             sm_tbeg.prev = t;
702         }
703         sm_tbeg = t;
704         ++sm_tlen;
705     }
706 
707 
708     //
709     // Remove a thread from the global thread list.
710     //
711     static void remove(ThreadBase t) nothrow @nogc
712     in
713     {
714         assert(t);
715     }
716     do
717     {
718         // Thread was already removed earlier, might happen b/c of thread_detachInstance
719         if (!t.next && !t.prev && (sm_tbeg !is t))
720             return;
721 
722         slock.lock_nothrow();
723         {
724             // NOTE: When a thread is removed from the global thread list its
725             //       main context is invalid and should be removed as well.
726             //       It is possible that t.m_curr could reference more
727             //       than just the main context if the thread exited abnormally
728             //       (if it was terminated), but we must assume that the user
729             //       retains a reference to them and that they may be re-used
730             //       elsewhere.  Therefore, it is the responsibility of any
731             //       object that creates contexts to clean them up properly
732             //       when it is done with them.
733             remove(&t.m_main);
734 
735             if (t.prev)
736                 t.prev.next = t.next;
737             if (t.next)
738                 t.next.prev = t.prev;
739             if (sm_tbeg is t)
740                 sm_tbeg = t.next;
741             t.prev = t.next = null;
742             --sm_tlen;
743         }
744         // NOTE: Don't null out t.next or t.prev because opApply currently
745         //       follows t.next after removing a node.  This could be easily
746         //       addressed by simply returning the next node from this
747         //       function, however, a thread should never be re-added to the
748         //       list anyway and having next and prev be non-null is a good way
749         //       to ensure that.
750         slock.unlock_nothrow();
751     }
752 }
753 
754 
755 ///////////////////////////////////////////////////////////////////////////////
756 // GC Support Routines
757 ///////////////////////////////////////////////////////////////////////////////
758 
759 pragma(mangle, "_D6strand8osthread12attachThreadFNbNiCQBk10threadbase10ThreadBaseZQBd")
760 ThreadBase function(ThreadBase) @nogc nothrow attachThread;
761 
762 extern (C) void _d_monitordelete_nogc(Object h) @nogc nothrow;
763 
764 /**
765  * Terminates the thread module. No other thread routine may be called
766  * afterwards.
767  */
768 package void thread_term_tpl(ThreadT, MainThreadStore)(ref MainThreadStore _mainThreadStore) @nogc nothrow
769 {
770     assert(_mainThreadStore.ptr is cast(void*) ThreadBase.sm_main);
771 
772     // destruct manually as object.destroy is not @nogc
773     (cast(ThreadT) cast(void*) ThreadBase.sm_main).__dtor();
774     _d_monitordelete_nogc(ThreadBase.sm_main);
775     _mainThreadStore[] = __traits(initSymbol, ThreadT)[];
776     ThreadBase.sm_main = null;
777 
778     assert(ThreadBase.sm_tbeg && ThreadBase.sm_tlen == 1);
779     assert(!ThreadBase.nAboutToStart);
780     if (ThreadBase.pAboutToStart) // in case realloc(p, 0) doesn't return null
781     {
782         free(ThreadBase.pAboutToStart);
783         ThreadBase.pAboutToStart = null;
784     }
785     ThreadBase.termLocks();
786     termLowlevelThreads();
787 }
788 
789 
790 /**
791  *
792  */
793 extern (C) bool thread_isMainThread() nothrow @nogc
794 {
795     return ThreadBase.getThis() is ThreadBase.sm_main;
796 }
797 
798 
799 /**
800  * Registers the calling thread for use with the D Runtime.  If this routine
801  * is called for a thread which is already registered, no action is performed.
802  *
803  * NOTE: This routine does not run thread-local static constructors when called.
804  *       If full functionality as a D thread is desired, the following function
805  *       must be called after thread_attachThis:
806  *
807  *       extern (C) void rt_moduleTlsCtor();
808  */
809 package ThreadT thread_attachThis_tpl(ThreadT)()
810 {
811     if (auto t = ThreadT.getThis())
812         return t;
813 
814     return cast(ThreadT) attachThread(new ThreadT());
815 }
816 
817 
818 /**
819  * Deregisters the calling thread from use with the runtime.  If this routine
820  * is called for a thread which is not registered, the result is undefined.
821  *
822  * NOTE: This routine does not run thread-local static destructors when called.
823  *       If full functionality as a D thread is desired, the following function
824  *       must be called before thread_detachThis, particularly if the thread is
825  *       being detached at some indeterminate time before program termination:
826  *
827  *       $(D extern(C) void rt_moduleTlsDtor();)
828  *
829  * See_Also:
830  *     $(REF thread_attachThis, core,thread,osthread)
831  */
832 extern (C) void thread_detachThis() nothrow @nogc
833 {
834     if (auto t = ThreadBase.getThis())
835         ThreadBase.remove(t);
836 }
837 
838 
839 /**
840  * Deregisters the given thread from use with the runtime.  If this routine
841  * is called for a thread which is not registered, the result is undefined.
842  *
843  * NOTE: This routine does not run thread-local static destructors when called.
844  *       If full functionality as a D thread is desired, the following function
845  *       must be called by the detached thread, particularly if the thread is
846  *       being detached at some indeterminate time before program termination:
847  *
848  *       $(D extern(C) void rt_moduleTlsDtor();)
849  */
850 extern (C) void thread_detachByAddr(ThreadID addr)
851 {
852     if (auto t = thread_findByAddr(addr))
853         ThreadBase.remove(t);
854 }
855 
856 
857 /// ditto
858 extern (C) void thread_detachInstance(ThreadBase t) nothrow @nogc
859 {
860     ThreadBase.remove(t);
861 }
862 
863 
864 /**
865  * Search the list of all threads for a thread with the given thread identifier.
866  *
867  * Params:
868  *  addr = The thread identifier to search for.
869  * Returns:
870  *  The thread object associated with the thread identifier, null if not found.
871  */
872 static ThreadBase thread_findByAddr(ThreadID addr)
873 {
874     ThreadBase.slock.lock_nothrow();
875     scope(exit) ThreadBase.slock.unlock_nothrow();
876 
877     // also return just spawned thread so that
878     // DLL_THREAD_ATTACH knows it's a D thread
879     foreach (t; ThreadBase.pAboutToStart[0 .. ThreadBase.nAboutToStart])
880         if (t.m_addr == addr)
881             return t;
882 
883     foreach (t; ThreadBase)
884         if (t.m_addr == addr)
885             return t;
886 
887     return null;
888 }
889 
890 
891 /**
892  * Sets the current thread to a specific reference. Only to be used
893  * when dealing with externally-created threads (in e.g. C code).
894  * The primary use of this function is when ThreadBase.getThis() must
895  * return a sensible value in, for example, TLS destructors. In
896  * other words, don't touch this unless you know what you're doing.
897  *
898  * Params:
899  *  t = A reference to the current thread. May be null.
900  */
901 extern (C) void thread_setThis(ThreadBase t) nothrow @nogc
902 {
903     ThreadBase.setThis(t);
904 }
905 
906 
907 /**
908  * Joins all non-daemon threads that are currently running.  This is done by
909  * performing successive scans through the thread list until a scan consists
910  * of only daemon threads.
911  */
912 extern (C) void thread_joinAll()
913 {
914  Lagain:
915     ThreadBase.slock.lock_nothrow();
916     // wait for just spawned threads
917     if (ThreadBase.nAboutToStart)
918     {
919         ThreadBase.slock.unlock_nothrow();
920         ThreadBase.yield();
921         goto Lagain;
922     }
923 
924     // join all non-daemon threads, the main thread is also a daemon
925     auto t = ThreadBase.sm_tbeg;
926     while (t)
927     {
928         if (!t.isRunning)
929         {
930             auto tn = t.next;
931             ThreadBase.remove(t);
932             t = tn;
933         }
934         else if (t.isDaemon)
935         {
936             t = t.next;
937         }
938         else
939         {
940             ThreadBase.slock.unlock_nothrow();
941             t.join(); // might rethrow
942             goto Lagain; // must restart iteration b/c of unlock
943         }
944     }
945     ThreadBase.slock.unlock_nothrow();
946 }
947 
948 
949 /**
950  * Performs intermediate shutdown of the thread module.
951  */
952 shared static ~this()
953 {
954     // NOTE: The functionality related to garbage collection must be minimally
955     //       operable after this dtor completes.  Therefore, only minimal
956     //       cleanup may occur.
957     auto t = ThreadBase.sm_tbeg;
958     while (t)
959     {
960         auto tn = t.next;
961         if (!t.isRunning)
962             ThreadBase.remove(t);
963         t = tn;
964     }
965 }
966 
967 // Used for needLock below.
968 package __gshared bool multiThreadedFlag = false;
969 
970 // Used for suspendAll/resumeAll below.
971 package __gshared uint suspendDepth = 0;
972 
973 pragma(mangle, "_D6strand8osthread6resumeFNbNiCQBd10threadbase10ThreadBaseZv")
974 extern(D) void function(ThreadBase) nothrow @nogc resume;
975 
976 /**
977  * Resume all threads but the calling thread for "stop the world" garbage
978  * collection runs.  This function must be called once for each preceding
979  * call to thread_suspendAll before the threads are actually resumed.
980  *
981  * In:
982  *  This routine must be preceded by a call to thread_suspendAll.
983  *
984  * Throws:
985  *  ThreadError if the resume operation fails for a running thread.
986  */
987 extern (C) void thread_resumeAll() nothrow
988 in
989 {
990     assert(suspendDepth > 0);
991 }
992 do
993 {
994     // NOTE: See thread_suspendAll for the logic behind this.
995     if (!multiThreadedFlag && ThreadBase.sm_tbeg)
996     {
997         if (--suspendDepth == 0)
998             resume(ThreadBase.getThis());
999         return;
1000     }
1001 
1002     scope(exit) ThreadBase.slock.unlock_nothrow();
1003     {
1004         if (--suspendDepth > 0)
1005             return;
1006 
1007         for (ThreadBase t = ThreadBase.sm_tbeg; t; t = t.next)
1008         {
1009             // NOTE: We do not need to care about critical regions at all
1010             //       here. thread_suspendAll takes care of everything.
1011             resume(t);
1012         }
1013     }
1014 }
1015 
1016 /**
1017  * Indicates the kind of scan being performed by $(D thread_scanAllType).
1018  */
1019 enum ScanType
1020 {
1021     stack, /// The stack and/or registers are being scanned.
1022     tls, /// TLS data is being scanned.
1023 }
1024 
1025 alias ScanAllThreadsFn = void delegate(void*, void*) nothrow; /// The scanning function.
1026 alias ScanAllThreadsTypeFn = void delegate(ScanType, void*, void*) nothrow; /// ditto
1027 
1028 /**
1029  * The main entry point for garbage collection.  The supplied delegate
1030  * will be passed ranges representing both stack and register values.
1031  *
1032  * Params:
1033  *  scan        = The scanner function.  It should scan from p1 through p2 - 1.
1034  *
1035  * In:
1036  *  This routine must be preceded by a call to thread_suspendAll.
1037  */
1038 extern (C) void thread_scanAllType(scope ScanAllThreadsTypeFn scan) nothrow
1039 in
1040 {
1041     assert(suspendDepth > 0);
1042 }
1043 do
1044 {
1045     callWithStackShell(sp => scanAllTypeImpl(scan, sp));
1046 }
1047 
1048 package alias callWithStackShellDg = void delegate(void* sp) nothrow;
1049 pragma(mangle, "_D6strand8osthread18callWithStackShellFNbMDFNbPvZvZv")
1050 extern(D) void function(scope callWithStackShellDg) nothrow callWithStackShell;
1051 
1052 private void scanAllTypeImpl(scope ScanAllThreadsTypeFn scan, void* curStackTop) nothrow
1053 {
1054     ThreadBase  thisThread  = null;
1055     void*   oldStackTop = null;
1056 
1057     if (ThreadBase.sm_tbeg)
1058     {
1059         thisThread  = ThreadBase.getThis();
1060         if (!thisThread.m_lock)
1061         {
1062             oldStackTop = thisThread.m_curr.tstack;
1063             thisThread.m_curr.tstack = curStackTop;
1064         }
1065     }
1066 
1067     scope(exit)
1068     {
1069         if (ThreadBase.sm_tbeg)
1070         {
1071             if (!thisThread.m_lock)
1072             {
1073                 thisThread.m_curr.tstack = oldStackTop;
1074             }
1075         }
1076     }
1077 
1078     // NOTE: Synchronizing on ThreadBase.slock is not needed because this
1079     //       function may only be called after all other threads have
1080     //       been suspended from within the same lock.
1081     if (ThreadBase.nAboutToStart)
1082         scan(ScanType.stack, ThreadBase.pAboutToStart, ThreadBase.pAboutToStart + ThreadBase.nAboutToStart);
1083 
1084     for (StackContext* c = ThreadBase.sm_cbeg; c; c = c.next)
1085     {
1086         static if (isStackGrowingDown)
1087         {
1088             assert(c.tstack <= c.bstack, "stack bottom can't be less than top");
1089 
1090             // NOTE: We can't index past the bottom of the stack
1091             //       so don't do the "+1" if isStackGrowingDown.
1092             if (c.tstack && c.tstack < c.bstack)
1093                 scan(ScanType.stack, c.tstack, c.bstack);
1094         }
1095         else
1096         {
1097             assert(c.bstack <= c.tstack, "stack top can't be less than bottom");
1098 
1099             if (c.bstack && c.bstack < c.tstack)
1100                 scan(ScanType.stack, c.bstack, c.tstack + 1);
1101         }
1102     }
1103 
1104     for (ThreadBase t = ThreadBase.sm_tbeg; t; t = t.next)
1105     {
1106         version (Windows)
1107         {
1108             // Ideally, we'd pass ScanType.regs or something like that, but this
1109             // would make portability annoying because it only makes sense on Windows.
1110             scanWindowsOnly(scan, t);
1111         }
1112 
1113         if (t.m_tlsgcdata !is null)
1114             rt_tlsgc_scan(t.m_tlsgcdata, (p1, p2) => scan(ScanType.tls, p1, p2));
1115     }
1116 }
1117 
1118 version (Windows)
1119 {
1120     // Currently scanWindowsOnly can't be handled properly by externDFunc
1121     // https://github.com/dlang/druntime/pull/3135#issuecomment-643673218
1122     pragma(mangle, "_D4core6thread8osthread15scanWindowsOnlyFNbMDFNbEQBvQBt10threadbase8ScanTypePvQcZvCQDdQDbQBi10ThreadBaseZv")
1123     private extern (D) void scanWindowsOnly(scope ScanAllThreadsTypeFn scan, ThreadBase) nothrow;
1124 }
1125 
1126 /**
1127  * The main entry point for garbage collection.  The supplied delegate
1128  * will be passed ranges representing both stack and register values.
1129  *
1130  * Params:
1131  *  scan        = The scanner function.  It should scan from p1 through p2 - 1.
1132  *
1133  * In:
1134  *  This routine must be preceded by a call to thread_suspendAll.
1135  */
1136 extern (C) void thread_scanAll(scope ScanAllThreadsFn scan) nothrow
1137 {
1138     thread_scanAllType((type, p1, p2) => scan(p1, p2));
1139 }
1140 
1141 pragma(mangle, "_D6strand8osthread12thread_yieldFNbNiZv")
1142 void function() @nogc nothrow thread_yield;
1143 
1144 /**
1145  * Signals that the code following this call is a critical region. Any code in
1146  * this region must finish running before the calling thread can be suspended
1147  * by a call to thread_suspendAll.
1148  *
1149  * This function is, in particular, meant to help maintain garbage collector
1150  * invariants when a lock is not used.
1151  *
1152  * A critical region is exited with thread_exitCriticalRegion.
1153  *
1154  * $(RED Warning):
1155  * Using critical regions is extremely error-prone. For instance, using locks
1156  * inside a critical region can easily result in a deadlock when another thread
1157  * holding the lock already got suspended.
1158  *
1159  * The term and concept of a 'critical region' comes from
1160  * $(LINK2 https://github.com/mono/mono/blob/521f4a198e442573c400835ef19bbb36b60b0ebb/mono/metadata/sgen-gc.h#L925, Mono's SGen garbage collector).
1161  *
1162  * In:
1163  *  The calling thread must be attached to the runtime.
1164  */
1165 extern (C) void thread_enterCriticalRegion() @nogc
1166 in
1167 {
1168     assert(ThreadBase.getThis());
1169 }
1170 do
1171 {
1172     synchronized (ThreadBase.criticalRegionLock)
1173         ThreadBase.getThis().m_isInCriticalRegion = true;
1174 }
1175 
1176 
1177 /**
1178  * Signals that the calling thread is no longer in a critical region. Following
1179  * a call to this function, the thread can once again be suspended.
1180  *
1181  * In:
1182  *  The calling thread must be attached to the runtime.
1183  */
1184 extern (C) void thread_exitCriticalRegion() @nogc
1185 in
1186 {
1187     assert(ThreadBase.getThis());
1188 }
1189 do
1190 {
1191     synchronized (ThreadBase.criticalRegionLock)
1192         ThreadBase.getThis().m_isInCriticalRegion = false;
1193 }
1194 
1195 
1196 /**
1197  * Returns true if the current thread is in a critical region; otherwise, false.
1198  *
1199  * In:
1200  *  The calling thread must be attached to the runtime.
1201  */
1202 extern (C) bool thread_inCriticalRegion() @nogc
1203 in
1204 {
1205     assert(ThreadBase.getThis());
1206 }
1207 do
1208 {
1209     synchronized (ThreadBase.criticalRegionLock)
1210         return ThreadBase.getThis().m_isInCriticalRegion;
1211 }
1212 
1213 
1214 /**
1215 * A callback for thread errors in D during collections. Since an allocation is not possible
1216 *  a preallocated ThreadError will be used as the Error instance
1217 *
1218 * Returns:
1219 *  never returns
1220 * Throws:
1221 *  ThreadError.
1222 */
1223 package void onThreadError(string msg) nothrow @nogc
1224 {
1225     __gshared ThreadError error = new ThreadError(null);
1226     error.msg = msg;
1227     error.next = null;
1228     error.info = SuppressTraceInfo.instance;
1229     throw error;
1230 }
1231 
1232 package class SuppressTraceInfo : Throwable.TraceInfo
1233 {
1234     override int opApply(scope int delegate(ref const(char[]))) const { return 0; }
1235     override int opApply(scope int delegate(ref size_t, ref const(char[]))) const { return 0; }
1236     override string toString() const { return null; }
1237     static SuppressTraceInfo instance() @trusted @nogc pure nothrow
1238     {
1239         static immutable SuppressTraceInfo it = new SuppressTraceInfo;
1240         return cast(SuppressTraceInfo)it;
1241     }
1242 }
1243 
1244 
1245 unittest
1246 {
1247     assert(!thread_inCriticalRegion());
1248 
1249     {
1250         thread_enterCriticalRegion();
1251 
1252         scope (exit)
1253             thread_exitCriticalRegion();
1254 
1255         assert(thread_inCriticalRegion());
1256     }
1257 
1258     assert(!thread_inCriticalRegion());
1259 }
1260 
1261 
1262 /**
1263  * Indicates whether an address has been marked by the GC.
1264  */
1265 enum IsMarked : int
1266 {
1267          no, /// Address is not marked.
1268         yes, /// Address is marked.
1269     unknown, /// Address is not managed by the GC.
1270 }
1271 
1272 alias IsMarkedDg = int delegate(void* addr) nothrow; /// The isMarked callback function.
1273 
1274 /**
1275  * This routine allows the runtime to process any special per-thread handling
1276  * for the GC.  This is needed for taking into account any memory that is
1277  * referenced by non-scanned pointers but is about to be freed.  That currently
1278  * means the array append cache.
1279  *
1280  * Params:
1281  *  isMarked = The function used to check if $(D addr) is marked.
1282  *
1283  * In:
1284  *  This routine must be called just prior to resuming all threads.
1285  */
1286 extern(C) void thread_processGCMarks(scope IsMarkedDg isMarked) nothrow
1287 {
1288     for (ThreadBase t = ThreadBase.sm_tbeg; t; t = t.next)
1289     {
1290         /* Can be null if collection was triggered between adding a
1291          * thread and calling rt_tlsgc_init.
1292          */
1293         if (t.m_tlsgcdata !is null)
1294             rt_tlsgc_processGCMarks(t.m_tlsgcdata, isMarked);
1295     }
1296 }
1297 
1298 
1299 /**
1300  * Returns the stack top of the currently active stack within the calling
1301  * thread.
1302  *
1303  * In:
1304  *  The calling thread must be attached to the runtime.
1305  *
1306  * Returns:
1307  *  The address of the stack top.
1308  */
1309 extern (C) void* thread_stackTop() nothrow @nogc
1310 in
1311 {
1312     // Not strictly required, but it gives us more flexibility.
1313     assert(ThreadBase.getThis());
1314 }
1315 do
1316 {
1317     return getStackTop();
1318 }
1319 
1320 
1321 /**
1322  * Returns the stack bottom of the currently active stack within the calling
1323  * thread.
1324  *
1325  * In:
1326  *  The calling thread must be attached to the runtime.
1327  *
1328  * Returns:
1329  *  The address of the stack bottom.
1330  */
1331 extern (C) void* thread_stackBottom() nothrow @nogc
1332 in (ThreadBase.getThis())
1333 {
1334     return ThreadBase.getThis().topContext().bstack;
1335 }
1336 
1337 
1338 ///////////////////////////////////////////////////////////////////////////////
1339 // lowlovel threading support
1340 ///////////////////////////////////////////////////////////////////////////////
1341 package
1342 {
1343     __gshared size_t ll_nThreads;
1344     __gshared ll_ThreadData* ll_pThreads;
1345 
1346     __gshared align(mutexAlign) void[mutexClassInstanceSize] ll_lock;
1347 
1348     @property Mutex lowlevelLock() nothrow @nogc
1349     {
1350         return cast(Mutex)ll_lock.ptr;
1351     }
1352 
1353     void initLowlevelThreads() @nogc nothrow
1354     {
1355         import core.lifetime : emplace;
1356         emplace(lowlevelLock());
1357     }
1358 
1359     void termLowlevelThreads() @nogc nothrow
1360     {
1361         lowlevelLock.__dtor();
1362     }
1363 
1364     void ll_removeThread(ThreadID tid) nothrow @nogc
1365     {
1366         lowlevelLock.lock_nothrow();
1367         scope(exit) lowlevelLock.unlock_nothrow();
1368 
1369         foreach (i; 0 .. ll_nThreads)
1370         {
1371             if (tid is ll_pThreads[i].tid)
1372             {
1373                 import core.stdc.string : memmove;
1374                 memmove(ll_pThreads + i, ll_pThreads + i + 1, ll_ThreadData.sizeof * (ll_nThreads - i - 1));
1375                 --ll_nThreads;
1376                 // no need to minimize, next add will do
1377                 break;
1378             }
1379         }
1380     }
1381 }
1382 
1383 /**
1384  * Check whether a thread was created by `createLowLevelThread`.
1385  *
1386  * Params:
1387  *  tid = the platform specific thread ID.
1388  *
1389  * Returns: `true` if the thread was created by `createLowLevelThread` and is still running.
1390  */
1391 bool findLowLevelThread(ThreadID tid) nothrow @nogc
1392 {
1393     lowlevelLock.lock_nothrow();
1394     scope(exit) lowlevelLock.unlock_nothrow();
1395 
1396     foreach (i; 0 .. ll_nThreads)
1397         if (tid is ll_pThreads[i].tid)
1398             return true;
1399     return false;
1400 }