-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathosthread.d
More file actions
2222 lines (1994 loc) · 68.3 KB
/
Copy pathosthread.d
File metadata and controls
2222 lines (1994 loc) · 68.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The osthread module provides low-level, OS-dependent code
* for thread creation and management.
*
* Copyright: Copyright Sean Kelly 2005 - 2012.
* License: Distributed under the
* $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
* (See accompanying file LICENSE)
* Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak
* Source: $(DRUNTIMESRC core/thread/osthread.d)
*/
module core.thread.osthread;
import core.atomic;
import core.internal.traits : externDFunc;
import core.memory : GC;
import core.thread.context;
import core.thread.threadbase;
import core.thread.types;
import core.time;
///////////////////////////////////////////////////////////////////////////////
// Platform Detection and Memory Allocation
///////////////////////////////////////////////////////////////////////////////
version (Posix)
public import core.thread.posix_impl;
else version (Windows)
public import core.thread.windows_impl;
else
static assert(false, "Unknown threading implementation.");
version (OSX)
version = Darwin;
else version (iOS)
version = Darwin;
else version (TVOS)
version = Darwin;
else version (WatchOS)
version = Darwin;
version (D_InlineAsm_X86)
{
version (Windows)
version = AsmX86_Windows;
else version (Posix)
version = AsmX86_Posix;
}
else version (D_InlineAsm_X86_64)
{
version (Windows)
{
version = AsmX86_64_Windows;
}
else version (Posix)
{
version = AsmX86_64_Posix;
}
}
version (Windows)
{
import core.stdc.stdint : uintptr_t; // for _beginthreadex decl below
import core.stdc.stdlib : free, malloc, realloc;
import core.sys.windows.basetsd /+: HANDLE+/;
import core.sys.windows.threadaux /+: getThreadStackBottom, impersonate_thread, OpenThreadHandle+/;
import core.sys.windows.winbase /+: CloseHandle, CREATE_SUSPENDED, DuplicateHandle, GetCurrentThread,
GetCurrentThreadId, GetCurrentProcess, GetExitCodeThread, GetSystemInfo, GetThreadContext,
GetThreadPriority, INFINITE, ResumeThread, SetThreadPriority, Sleep, STILL_ACTIVE,
SuspendThread, SwitchToThread, SYSTEM_INFO, THREAD_PRIORITY_IDLE, THREAD_PRIORITY_NORMAL,
THREAD_PRIORITY_TIME_CRITICAL, WAIT_OBJECT_0, WaitForSingleObject+/;
import core.sys.windows.windef /+: TRUE+/;
import core.sys.windows.winnt /+: CONTEXT, CONTEXT_CONTROL, CONTEXT_INTEGER+/;
private extern (Windows) alias btex_fptr = uint function(void*);
private extern (C) uintptr_t _beginthreadex(void*, uint, btex_fptr, void*, uint, uint*) nothrow @nogc;
}
else version (Posix)
{
static import core.sys.posix.pthread;
import core.stdc.errno : EINTR, errno;
version (CRuntime_WASI)
import core.sys.posix.pthread : pthread_attr_destroy, pthread_attr_getstack,
pthread_attr_init, pthread_attr_setstacksize, pthread_create, pthread_detach,
pthread_join, pthread_self, sched_yield;
else
{
static import core.sys.posix.signal;
import core.sys.posix.pthread : pthread_atfork, pthread_attr_destroy, pthread_attr_getstack,
pthread_attr_init, pthread_attr_setstacksize, pthread_create, pthread_detach, pthread_getschedparam,
pthread_join, pthread_self, pthread_setschedparam, sched_get_priority_max, sched_get_priority_min,
sched_param, sched_yield;
import core.sys.posix.semaphore : sem_init, sem_post, sem_t, sem_wait;
import core.sys.posix.signal : pthread_kill, sigaction, sigaction_t, sigdelset, sigfillset, sigset_t, sigsuspend,
SIGUSR1, stack_t;
}
import core.sys.posix.stdlib : free, malloc, realloc;
import core.sys.posix.sys.types : pthread_attr_t, pthread_key_t, pthread_t;
import core.sys.posix.time : nanosleep, timespec;
version (Darwin)
{
// Use macOS threads for suspend/resume
import core.sys.darwin.mach.kern_return : KERN_SUCCESS;
import core.sys.darwin.mach.port : mach_port_t;
import core.sys.darwin.mach.thread_act : mach_msg_type_number_t,
thread_get_state, thread_resume, thread_suspend;
import core.sys.darwin.pthread : pthread_mach_thread_np;
version (X86)
{
import core.sys.darwin.mach.thread_act :
x86_THREAD_STATE32, x86_THREAD_STATE32_COUNT, x86_thread_state32_t;
}
else version (X86_64)
{
import core.sys.darwin.mach.thread_act :
x86_THREAD_STATE64, x86_THREAD_STATE64_COUNT, x86_thread_state64_t;
}
else version (AArch64)
{
import core.sys.darwin.mach.thread_act :
ARM_THREAD_STATE64, ARM_THREAD_STATE64_COUNT, arm_thread_state64_t;
}
else version (PPC)
{
import core.sys.darwin.mach.thread_act :
PPC_THREAD_STATE, PPC_THREAD_STATE_COUNT, ppc_thread_state_t;
}
else version (PPC64)
{
import core.sys.darwin.mach.thread_act :
PPC_THREAD_STATE64, PPC_THREAD_STATE64_COUNT, ppc_thread_state64_t;
}
}
else version (Solaris)
{
// Use Solaris threads for suspend/resume
import core.sys.posix.sys.wait : idtype_t;
import core.sys.solaris.sys.priocntl : PC_CLNULL, PC_GETCLINFO, PC_GETPARMS, PC_SETPARMS, pcinfo_t, pcparms_t, priocntl;
import core.sys.solaris.sys.types : P_MYID, pri_t;
import core.sys.solaris.thread : thr_stksegment, thr_suspend, thr_continue;
import core.sys.solaris.sys.procfs : PR_STOPPED, lwpstatus_t;
}
else
{
// Use POSIX threads for suspend/resume
}
}
else
static assert(0, "unsupported operating system");
version (GNU)
{
import gcc.builtins;
}
/**
* Hook for whatever EH implementation is used to save/restore some data
* per stack.
*
* Params:
* newContext = The return value of the prior call to this function
* where the stack was last swapped out, or null when a fiber stack
* is switched in for the first time.
*/
private extern(C) void* _d_eh_swapContext(void* newContext) nothrow @nogc;
version (DigitalMars)
{
version (Windows)
{
extern(D) void* swapContext(void* newContext) nothrow @nogc
{
return _d_eh_swapContext(newContext);
}
}
else
{
extern(C) void* _d_eh_swapContextDwarf(void* newContext) nothrow @nogc;
extern(D) void* swapContext(void* newContext) nothrow @nogc
{
/* Detect at runtime which scheme is being used.
* Eventually, determine it statically.
*/
static int which = 0;
final switch (which)
{
case 0:
{
assert(newContext == null);
auto p = _d_eh_swapContext(newContext);
auto pdwarf = _d_eh_swapContextDwarf(newContext);
if (p)
{
which = 1;
return p;
}
else if (pdwarf)
{
which = 2;
return pdwarf;
}
return null;
}
case 1:
return _d_eh_swapContext(newContext);
case 2:
return _d_eh_swapContextDwarf(newContext);
}
}
}
}
else
{
extern(D) void* swapContext(void* newContext) nothrow @nogc
{
return _d_eh_swapContext(newContext);
}
}
/**
* This class encapsulates all threading functionality for the D
* programming language. As thread manipulation is a required facility
* for garbage collection, all user threads should derive from this
* class, and instances of this class should never be explicitly deleted.
* A new thread may be created using either derivation or composition, as
* in the following example.
*/
version (CoreDdoc)
class Thread : ThreadBase
{
/**
* Initializes a thread object which is associated with a static
* D function.
*
* Params:
* fn = The thread function.
* sz = The stack size for this thread.
*
* In:
* fn must not be null.
*/
this( void function() fn, size_t sz = 0 ) @safe pure nothrow @nogc
{
}
/**
* Initializes a thread object which is associated with a dynamic
* D function.
*
* Params:
* dg = The thread function.
* sz = The stack size for this thread.
*
* In:
* dg must not be null.
*/
this( void delegate() dg, size_t sz = 0 ) @safe pure nothrow @nogc
{
}
package this( size_t sz = 0 ) @safe pure nothrow @nogc
{
}
/**
* Cleans up any remaining resources used by this object.
*/
~this() nothrow @nogc
{
}
/**
* Provides a reference to the calling thread.
*
* Returns:
* The thread object representing the calling thread. The result of
* deleting this object is undefined. If the current thread is not
* attached to the runtime, a null reference is returned.
*/
static Thread getThis() @safe nothrow @nogc
{
return null;
}
///
override final void[] savedRegisters() nothrow @nogc
{
return null;
}
/**
* Starts the thread and invokes the function or delegate passed upon
* construction.
*
* In:
* This routine may only be called once per thread instance.
*
* Throws:
* ThreadException if the thread fails to start.
*/
final Thread start() nothrow
{
return null;
}
/**
* Waits for this thread to complete. If the thread terminated as the
* result of an unhandled exception, this exception will be rethrown.
*
* Params:
* rethrow = Rethrow any unhandled exception which may have caused this
* thread to terminate.
*
* Throws:
* ThreadException if the operation fails.
* Any exception not handled by the joined thread.
*
* Returns:
* Any exception not handled by this thread if rethrow = false, null
* otherwise.
*/
override final Throwable join( bool rethrow = true )
{
return null;
}
/**
* The minimum scheduling priority that may be set for a thread. On
* systems where multiple scheduling policies are defined, this value
* represents the minimum valid priority for the scheduling policy of
* the process.
*/
@property static int PRIORITY_MIN() @nogc nothrow pure @trusted
{
return 0;
}
/**
* The maximum scheduling priority that may be set for a thread. On
* systems where multiple scheduling policies are defined, this value
* represents the maximum valid priority for the scheduling policy of
* the process.
*/
@property static const(int) PRIORITY_MAX() @nogc nothrow pure @trusted
{
return 0;
}
/**
* The default scheduling priority that is set for a thread. On
* systems where multiple scheduling policies are defined, this value
* represents the default priority for the scheduling policy of
* the process.
*/
@property static int PRIORITY_DEFAULT() @nogc nothrow pure @trusted
{
return 0;
}
/**
* Gets the scheduling priority for the associated thread.
*
* Note: Getting the priority of a thread that already terminated
* might return the default priority.
*
* Returns:
* The scheduling priority of this thread.
*/
final @property int priority()
{
return 0;
}
/**
* Sets the scheduling priority for the associated thread.
*
* Note: Setting the priority of a thread that already terminated
* might have no effect.
*
* Params:
* val = The new scheduling priority of this thread.
*/
final @property void priority( int val )
{
}
/**
* Tests whether this thread is running.
*
* Returns:
* true if the thread is running, false if not.
*/
override final @property bool isRunning() nothrow @nogc
{
return false;
}
/**
* Suspends the calling thread for at least the supplied period. This may
* result in multiple OS calls if period is greater than the maximum sleep
* duration supported by the operating system.
*
* Params:
* val = The minimum duration the calling thread should be suspended.
*
* In:
* period must be non-negative.
*
* Example:
* ------------------------------------------------------------------------
*
* Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
* Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
*
* ------------------------------------------------------------------------
*/
static void sleep( Duration val ) @nogc nothrow @trusted
{
}
/**
* Forces a context switch to occur away from the calling thread.
*/
static void yield() @nogc nothrow
{
}
}
package Thread toThread(return scope ThreadBase t) @trusted nothrow @nogc pure
{
return cast(Thread) cast(void*) t;
}
private extern(D) static void thread_yield() @nogc nothrow
{
Thread.yield();
}
///
static if (!isSingleThreaded)
unittest
{
class DerivedThread : Thread
{
this()
{
super(&run);
}
private:
void run()
{
// Derived thread running.
}
}
void threadFunc()
{
// Composed thread running.
}
// create and start instances of each type
auto derived = new DerivedThread().start();
auto composed = new Thread(&threadFunc).start();
new Thread({
// Codes to run in the newly created thread.
}).start();
}
static if (!isSingleThreaded)
unittest
{
int x = 0;
new Thread(
{
x++;
}).start().join();
assert( x == 1 );
}
static if (!isSingleThreaded)
unittest
{
enum MSG = "Test message.";
string caughtMsg;
try
{
new Thread(
function()
{
throw new Exception( MSG );
}).start().join();
assert( false, "Expected rethrown exception." );
}
catch ( Throwable t )
{
assert( t.msg == MSG );
}
}
static if (!isSingleThreaded)
unittest
{
// use >pageSize to avoid stack overflow (e.g. in an syscall)
auto thr = new Thread(function{}, 4096 + 1).start();
thr.join();
}
static if (!isSingleThreaded)
unittest
{
import core.memory : GC;
auto t1 = new Thread({
foreach (_; 0 .. 20)
ThreadBase.getAll;
}).start;
auto t2 = new Thread({
foreach (_; 0 .. 20)
GC.collect;
}).start;
t1.join();
t2.join();
}
static if (!isSingleThreaded)
unittest
{
import core.sync.semaphore;
auto sem = new Semaphore();
auto t = new Thread(
{
sem.notify();
Thread.sleep(100.msecs);
}).start();
sem.wait(); // thread cannot be detached while being started
thread_detachInstance(t);
foreach (t2; Thread)
assert(t !is t2);
t.join();
}
// https://issues.dlang.org/show_bug.cgi?id=22124
unittest
{
Thread thread = new Thread({});
auto fun(Thread t, int x)
{
t.__ctor({x = 3;});
return t;
}
static assert(!__traits(compiles, () @nogc => fun(thread, 3) ));
}
@nogc @safe nothrow
unittest
{
Thread.sleep(1.msecs);
}
unittest
{
with(Thread)
{
auto thr = Thread.getThis();
immutable prio = thr.priority;
scope (exit) thr.priority = prio;
assert(prio == PRIORITY_DEFAULT);
assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX);
thr.priority = PRIORITY_MIN;
assert(thr.priority == PRIORITY_MIN);
thr.priority = PRIORITY_MAX;
assert(thr.priority == PRIORITY_MAX);
}
}
static if (!isSingleThreaded)
unittest // Bugzilla 8960
{
import core.sync.semaphore;
with(Thread)
{
auto thr = new Thread({});
thr.start();
Thread.sleep(1.msecs); // wait a little so the thread likely has finished
thr.priority = PRIORITY_MAX; // setting priority doesn't cause error
auto prio = thr.priority; // getting priority doesn't cause error
assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX);
}
}
///////////////////////////////////////////////////////////////////////////////
// GC Support Routines
///////////////////////////////////////////////////////////////////////////////
version (CoreDdoc)
{
/**
* Instruct the thread module, when initialized, to use a different set of
* signals besides SIGRTMIN and SIGRTMIN + 1 for suspension and resumption of threads.
* This function should be called at most once, prior to thread_init().
* This function is Posix-only.
*/
extern (C) void thread_setGCSignals(int suspendSignalNo, int resumeSignalNo) nothrow @nogc
{
}
/**
* Get the GC signals set by the thread module. This function should be called either
* after thread_init() has finished, or after a call thread_setGCSignals().
* This function is Posix-only.
*/
extern (C) void thread_getGCSignals(out int suspendSignalNo, out int resumeSignalNo) nothrow @nogc
{
}
}
version (CoreDdoc) {} else
private extern (D) ThreadBase attachThread(ThreadBase _thisThread) @nogc nothrow
{
Thread thisThread = _thisThread.toThread();
StackContext* thisContext = &thisThread.m_main;
assert( thisContext == thisThread.m_curr );
thisThread.m_tdescr = Thread.getCurrentThreadDescr();
thisContext.bstack = getStackBottom();
thisContext.tstack = thisContext.bstack;
version (Posix)
atomicStore!(MemoryOrder.raw)(thisThread.toThread.m_isRunning, true);
thisThread.m_isDaemon = true;
thisThread.tlsRTdataInit();
Thread.setThis( thisThread );
Thread.add( thisThread, false );
Thread.add( thisContext );
if ( Thread.sm_main !is null )
multiThreadedFlag = true;
return thisThread;
}
/**
* Registers the calling thread for use with the D Runtime. If this routine
* is called for a thread which is already registered, no action is performed.
*
* NOTE: This routine does not run thread-local static constructors when called.
* If full functionality as a D thread is desired, the following function
* must be called after thread_attachThis:
*
* extern (C) void rt_moduleTlsCtor();
*
* See_Also:
* $(REF thread_detachThis, core,thread,threadbase)
*/
extern(C) Thread thread_attachThis()
{
return thread_attachThis_tpl!Thread();
}
version (Windows)
{
// NOTE: These calls are not safe on Posix systems that use signals to
// perform garbage collection. The suspendHandler uses getThis()
// to get the thread handle so getThis() must be a simple call.
// Mutexes can't safely be acquired inside signal handlers, and
// even if they could, the mutex needed (Thread.slock) is held by
// thread_suspendAll(). So in short, these routines will remain
// Windows-specific. If they are truly needed elsewhere, the
// suspendHandler will need a way to call a version of getThis()
// that only does the TLS lookup without the fancy fallback stuff.
/// ditto
extern (C) Thread thread_attachByAddr( ThreadID addr )
{
return thread_attachByAddrB( addr, getThreadStackBottom( addr ) );
}
/// ditto
extern (C) Thread thread_attachByAddrB( ThreadID addr, void* bstack )
{
GC.disable(); scope(exit) GC.enable();
if (auto t = thread_findByAddr(addr).toThread)
return t;
Thread thisThread = new Thread();
StackContext* thisContext = &thisThread.m_main;
assert( thisContext == thisThread.m_curr );
thisThread.m_tdescr.tid = addr;
thisContext.bstack = bstack;
thisContext.tstack = thisContext.bstack;
thisThread.m_isDaemon = true;
if ( addr == GetCurrentThreadId() )
{
thisThread.m_tdescr.hndl = GetCurrentThreadHandle();
thisThread.tlsRTdataInit();
Thread.setThis( thisThread );
}
else
{
thisThread.m_tdescr.hndl = OpenThreadHandle( addr );
impersonate_thread(addr,
{
thisThread.tlsRTdataInit();
Thread.setThis( thisThread );
});
}
Thread.add( thisThread, false );
Thread.add( thisContext );
if ( Thread.sm_main !is null )
multiThreadedFlag = true;
return thisThread;
}
}
// Calls the given delegate, passing the current thread's stack pointer to it.
package extern(D) void callWithStackShell(scope callWithStackShellDg fn) nothrow
in (fn)
{
// The purpose of the 'shell' is to ensure all the registers get
// put on the stack so they'll be scanned. We only need to push
// the callee-save registers.
void *sp = void;
version (GNU)
{
// The generic solution below using a call to __builtin_unwind_init ()
// followed by an assignment to sp has two issues:
// 1) On some archs it stores a huge amount of FP and Vector state which
// is not the subject of the scan - and, indeed might produce false
// hits.
// 2) Even on archs like X86, where there are no callee-saved FPRs/VRs there
// tend to be 'holes' in the frame allocations (to deal with alignment) which
// also will contain random data which could produce false positives.
// This solution stores only the integer callee-saved registers.
version (X86)
{
void*[3] regs = void;
asm pure nothrow @nogc
{
"movl %%ebx, %0" : "=m" (regs[0]);
"movl %%esi, %0" : "=m" (regs[1]);
"movl %%edi, %0" : "=m" (regs[2]);
}
sp = cast(void*)®s[0];
}
else version (X86_64)
{
void*[5] regs = void;
asm pure nothrow @nogc
{
"movq %%rbx, %0" : "=m" (regs[0]);
"movq %%r12, %0" : "=m" (regs[1]);
"movq %%r13, %0" : "=m" (regs[2]);
"movq %%r14, %0" : "=m" (regs[3]);
"movq %%r15, %0" : "=m" (regs[4]);
}
sp = cast(void*)®s[0];
}
else version (PPC)
{
void*[19] regs = void;
version (Darwin)
enum regname = "r";
else
enum regname = "";
static foreach (i; 0 .. regs.length)
{{
enum int j = 13 + i; // source register
asm pure nothrow @nogc
{
("stw "~regname~j.stringof~", %0") : "=m" (regs[i]);
}
}}
sp = cast(void*)®s[0];
}
else version (PPC64)
{
void*[19] regs = void;
version (Darwin)
enum regname = "r";
else
enum regname = "";
static foreach (i; 0 .. regs.length)
{{
enum int j = 13 + i; // source register
asm pure nothrow @nogc
{
("std "~regname~j.stringof~", %0") : "=m" (regs[i]);
}
}}
sp = cast(void*)®s[0];
}
else version (AArch64)
{
// Callee-save registers, x19-x28 according to AAPCS64, section
// 5.1.1. Include x29 fp because it optionally can be a callee
// saved reg
size_t[11] regs = void;
// store the registers in pairs
asm pure nothrow @nogc
{
"stp x19, x20, %0" : "=m" (regs[ 0]), "=m" (regs[1]);
"stp x21, x22, %0" : "=m" (regs[ 2]), "=m" (regs[3]);
"stp x23, x24, %0" : "=m" (regs[ 4]), "=m" (regs[5]);
"stp x25, x26, %0" : "=m" (regs[ 6]), "=m" (regs[7]);
"stp x27, x28, %0" : "=m" (regs[ 8]), "=m" (regs[9]);
"str x29, %0" : "=m" (regs[10]);
"mov %0, sp" : "=r" (sp);
}
}
else version (ARM)
{
// Callee-save registers, according to AAPCS, section 5.1.1.
// arm and thumb2 instructions
size_t[8] regs = void;
asm pure nothrow @nogc
{
"stm %0, {r4-r11}" : : "r" (regs.ptr) : "memory";
"mov %0, sp" : "=r" (sp);
}
}
else
{
__builtin_unwind_init();
sp = &sp;
}
}
else version (AsmX86_Posix)
{
size_t[3] regs = void;
asm pure nothrow @nogc
{
mov [regs + 0 * 4], EBX;
mov [regs + 1 * 4], ESI;
mov [regs + 2 * 4], EDI;
mov sp[EBP], ESP;
}
}
else version (AsmX86_Windows)
{
size_t[3] regs = void;
asm pure nothrow @nogc
{
mov [regs + 0 * 4], EBX;
mov [regs + 1 * 4], ESI;
mov [regs + 2 * 4], EDI;
mov sp[EBP], ESP;
}
}
else version (AsmX86_64_Posix)
{
size_t[5] regs = void;
asm pure nothrow @nogc
{
mov [regs + 0 * 8], RBX;
mov [regs + 1 * 8], R12;
mov [regs + 2 * 8], R13;
mov [regs + 3 * 8], R14;
mov [regs + 4 * 8], R15;
mov sp[RBP], RSP;
}
}
else version (AsmX86_64_Windows)
{
size_t[7] regs = void;
asm pure nothrow @nogc
{
mov [regs + 0 * 8], RBX;
mov [regs + 1 * 8], RSI;
mov [regs + 2 * 8], RDI;
mov [regs + 3 * 8], R12;
mov [regs + 4 * 8], R13;
mov [regs + 5 * 8], R14;
mov [regs + 6 * 8], R15;
mov sp[RBP], RSP;
}
}
else version (AArch64)
{
// Callee-save registers, x19-x28 according to AAPCS64, section
// 5.1.1. Include x29 fp because it optionally can be a callee
// saved reg
size_t[11] regs = void;
// store the registers in pairs
asm pure nothrow @nogc
{
/*
stp x19, x20, regs[0];
stp x21, x22, regs[2];
stp x23, x24, regs[4];
stp x25, x26, regs[6];
stp x27, x28, regs[8];
str x29, regs[10];
mov [sp], sp;
*/
}
assert(0, "implement AArch64 inline assembler for callWithStackShell()"); // TODO AArch64
}
else
{
static assert(false, "Architecture not supported.");
}
fn(sp);
}
/**
* Returns the process ID of the calling process, which is guaranteed to be
* unique on the system. This call is always successful.
*
* Example:
* ---
* writefln("Current process id: %s", getpid());
* ---
*/
version (Posix)
{
alias getpid = imported!"core.sys.posix.unistd".getpid;
}
else version (Windows)
{
alias getpid = imported!"core.sys.windows.winbase".GetCurrentProcessId;
}
else
static assert(0, "unsupported os");
extern (C) @nogc nothrow
{
version (CRuntime_Glibc) version = PThread_Getattr_NP;
version (CRuntime_Bionic) version = PThread_Getattr_NP;
version (CRuntime_Musl) version = PThread_Getattr_NP;
version (CRuntime_UClibc) version = PThread_Getattr_NP;
version (FreeBSD) version = PThread_Attr_Get_NP;
version (NetBSD) version = PThread_Attr_Get_NP;
version (DragonFlyBSD) version = PThread_Attr_Get_NP;
version (PThread_Getattr_NP) int pthread_getattr_np(pthread_t thread, pthread_attr_t* attr);
version (PThread_Attr_Get_NP) int pthread_attr_get_np(pthread_t thread, pthread_attr_t* attr);
version (OpenBSD) int pthread_stackseg_np(pthread_t thread, stack_t* sinfo);
}
private extern(D) void* getStackTop() nothrow @nogc
{
version (D_InlineAsm_X86)
asm pure nothrow @nogc { naked; mov EAX, ESP; ret; }
else version (D_InlineAsm_X86_64)
asm pure nothrow @nogc { naked; mov RAX, RSP; ret; }
else version (AArch64)
//asm pure nothrow @nogc { naked; mov x0, SP; ret; } // TODO AArch64
{
return null;
}
else version (GNU)
return __builtin_frame_address(0);
else
static assert(false, "Architecture not supported.");
}
private extern(D) void* getStackBottom() nothrow @nogc
{
version (Windows)
{
version (D_InlineAsm_X86)
asm pure nothrow @nogc { naked; mov EAX, FS:4; ret; }
else version (D_InlineAsm_X86_64)
asm pure nothrow @nogc
{ naked;
mov RAX, 8;
mov RAX, GS:[RAX];