-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
task.c
1403 lines (1314 loc) · 43.5 KB
/
task.c
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
// This file is a part of Julia. License is MIT: https://julialang.org/license
/*
task.c
lightweight processes (symmetric coroutines)
*/
// need this to get the real definition of ucontext_t,
// if we're going to use the ucontext_t implementation there
//#if defined(__APPLE__) && defined(JL_HAVE_UCONTEXT)
//#pragma push_macro("_XOPEN_SOURCE")
//#define _XOPEN_SOURCE
//#include <ucontext.h>
//#pragma pop_macro("_XOPEN_SOURCE")
//#endif
// this is needed for !COPY_STACKS to work on linux
#ifdef _FORTIFY_SOURCE
// disable __longjmp_chk validation so that we can jump between stacks
// (which would normally be invalid to do with setjmp / longjmp)
#pragma push_macro("_FORTIFY_SOURCE")
#undef _FORTIFY_SOURCE
#include <setjmp.h>
#pragma pop_macro("_FORTIFY_SOURCE")
#endif
#include "platform.h"
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <inttypes.h>
#include "julia.h"
#include "julia_internal.h"
#include "threading.h"
#include "julia_assert.h"
#include "support/hashing.h"
#ifdef __cplusplus
extern "C" {
#endif
#if defined(_COMPILER_ASAN_ENABLED_)
static inline void sanitizer_start_switch_fiber(const void* bottom, size_t size) {
__sanitizer_start_switch_fiber(NULL, bottom, size);
}
static inline void sanitizer_finish_switch_fiber(void) {
__sanitizer_finish_switch_fiber(NULL, NULL, NULL);
}
#else
static inline void sanitizer_start_switch_fiber(const void* bottom, size_t size) {}
static inline void sanitizer_finish_switch_fiber(void) {}
#endif
#if defined(_COMPILER_TSAN_ENABLED_)
static inline void tsan_destroy_ctx(jl_ptls_t ptls, void *state) {
if (state != &ptls->root_task->state) {
__tsan_destroy_fiber(ctx->state);
}
ctx->state = NULL;
}
static inline void tsan_switch_to_ctx(void *state) {
__tsan_switch_to_fiber(state, 0);
}
#endif
// empirically, jl_finish_task needs about 64k stack space to infer/run
// and additionally, gc-stack reserves 64k for the guard pages
#if defined(MINSIGSTKSZ)
#define MINSTKSZ (MINSIGSTKSZ > 131072 ? MINSIGSTKSZ : 131072)
#else
#define MINSTKSZ 131072
#endif
#define ROOT_TASK_STACK_ADJUSTMENT 3000000
#ifdef JL_HAVE_ASYNCIFY
// Switching logic is implemented in JavaScript
#define STATIC_OR_JS JL_DLLEXPORT
#else
#define STATIC_OR_JS static
#endif
extern size_t jl_page_size;
static char *jl_alloc_fiber(jl_ucontext_t *t, size_t *ssize, jl_task_t *owner) JL_NOTSAFEPOINT;
STATIC_OR_JS void jl_set_fiber(jl_ucontext_t *t);
STATIC_OR_JS void jl_swap_fiber(jl_ucontext_t *lastt, jl_ucontext_t *t);
STATIC_OR_JS void jl_start_fiber_swap(jl_ucontext_t *savet, jl_ucontext_t *t);
STATIC_OR_JS void jl_start_fiber_set(jl_ucontext_t *t);
#ifdef ALWAYS_COPY_STACKS
# ifndef COPY_STACKS
# error "ALWAYS_COPY_STACKS requires COPY_STACKS"
# endif
static int always_copy_stacks = 1;
#else
static int always_copy_stacks = 0;
#endif
#ifdef COPY_STACKS
static void memcpy_a16(uint64_t *to, uint64_t *from, size_t nb)
{
memcpy((char*)jl_assume_aligned(to, 16), (char*)jl_assume_aligned(from, 16), nb);
//uint64_t *end = (uint64_t*)((char*)from + nb);
//while (from < end)
// *(to++) = *(from++);
}
static void NOINLINE save_stack(jl_ptls_t ptls, jl_task_t *lastt, jl_task_t **pt)
{
char *frame_addr = (char*)((uintptr_t)jl_get_frame_addr() & ~15);
char *stackbase = (char*)ptls->stackbase;
assert(stackbase > frame_addr);
size_t nb = stackbase - frame_addr;
void *buf;
if (lastt->bufsz < nb) {
buf = (void*)jl_gc_alloc_buf(ptls, nb);
lastt->stkbuf = buf;
lastt->bufsz = nb;
}
else {
buf = lastt->stkbuf;
}
*pt = NULL; // clear the gc-root for the target task before copying the stack for saving
lastt->copy_stack = nb;
lastt->sticky = 1;
memcpy_a16((uint64_t*)buf, (uint64_t*)frame_addr, nb);
// this task's stack could have been modified after
// it was marked by an incremental collection
// move the barrier back instead of walking it again here
jl_gc_wb_back(lastt);
}
static void NOINLINE JL_NORETURN restore_stack(jl_task_t *t, jl_ptls_t ptls, char *p)
{
size_t nb = t->copy_stack;
char *_x = (char*)ptls->stackbase - nb;
if (!p) {
// switch to a stackframe that's beyond the bounds of the last switch
p = _x;
if ((char*)&_x > _x) {
p = (char*)alloca((char*)&_x - _x);
}
restore_stack(t, ptls, p); // pass p to ensure the compiler can't tailcall this or avoid the alloca
}
void *_y = t->stkbuf;
assert(_x != NULL && _y != NULL);
memcpy_a16((uint64_t*)_x, (uint64_t*)_y, nb); // destroys all but the current stackframe
sanitizer_start_switch_fiber(t->stkbuf, t->bufsz);
#if defined(_OS_WINDOWS_)
jl_setcontext(&t->ctx);
#else
jl_longjmp(t->copy_stack_ctx.uc_mcontext, 1);
#endif
abort(); // unreachable
}
static void restore_stack2(jl_task_t *t, jl_ptls_t ptls, jl_task_t *lastt)
{
assert(t->copy_stack && !lastt->copy_stack);
size_t nb = t->copy_stack;
char *_x = (char*)ptls->stackbase - nb;
void *_y = t->stkbuf;
assert(_x != NULL && _y != NULL);
memcpy_a16((uint64_t*)_x, (uint64_t*)_y, nb); // destroys all but the current stackframe
#if defined(JL_HAVE_UNW_CONTEXT)
volatile int returns = 0;
int r = unw_getcontext(&lastt->ctx);
if (++returns == 2) // r is garbage after the first return
return;
if (r != 0 || returns != 1)
abort();
#elif defined(JL_HAVE_ASM) || defined(JL_HAVE_SIGALTSTACK) || defined(_OS_WINDOWS_)
if (jl_setjmp(lastt->copy_stack_ctx.uc_mcontext, 0))
return;
#else
#error COPY_STACKS is incompatible with this platform
#endif
sanitizer_start_switch_fiber(t->stkbuf, t->bufsz);
#if defined(_OS_WINDOWS_)
jl_setcontext(&t->ctx);
#else
jl_longjmp(t->copy_stack_ctx.uc_mcontext, 1);
#endif
}
#endif
/* Rooted by the base module */
static jl_function_t *task_done_hook_func JL_GLOBALLY_ROOTED = NULL;
void JL_NORETURN jl_finish_task(jl_task_t *t)
{
jl_task_t *ct = jl_current_task;
JL_SIGATOMIC_BEGIN();
if (t->_isexception)
jl_atomic_store_release(&t->_state, JL_TASK_STATE_FAILED);
else
jl_atomic_store_release(&t->_state, JL_TASK_STATE_DONE);
if (t->copy_stack) // early free of stkbuf
t->stkbuf = NULL;
// ensure that state is cleared
ct->ptls->in_finalizer = 0;
ct->ptls->in_pure_callback = 0;
ct->world_age = jl_world_counter;
// let the runtime know this task is dead and find a new task to run
jl_function_t *done = jl_atomic_load_relaxed(&task_done_hook_func);
if (done == NULL) {
done = (jl_function_t*)jl_get_global(jl_base_module, jl_symbol("task_done_hook"));
if (done != NULL)
jl_atomic_store_release(&task_done_hook_func, done);
}
if (done != NULL) {
jl_value_t *args[2] = {done, (jl_value_t*)t};
JL_TRY {
jl_apply(args, 2);
}
JL_CATCH {
jl_no_exc_handler(jl_current_exception());
}
}
gc_debug_critical_error();
abort();
}
JL_DLLEXPORT void *jl_task_stack_buffer(jl_task_t *task, size_t *size, int *ptid)
{
size_t off = 0;
#ifndef _OS_WINDOWS_
if (jl_all_tls_states[0]->root_task == task) {
// See jl_init_root_task(). The root task of the main thread
// has its buffer enlarged by an artificial 3000000 bytes, but
// that means that the start of the buffer usually points to
// inaccessible memory. We need to correct for this.
off = ROOT_TASK_STACK_ADJUSTMENT;
}
#endif
jl_ptls_t ptls2 = task->ptls;
*ptid = -1;
if (ptls2) {
*ptid = task->tid;
#ifdef COPY_STACKS
if (task->copy_stack) {
*size = ptls2->stacksize;
return (char *)ptls2->stackbase - *size;
}
#endif
}
*size = task->bufsz - off;
return (void *)((char *)task->stkbuf + off);
}
JL_DLLEXPORT void jl_active_task_stack(jl_task_t *task,
char **active_start, char **active_end,
char **total_start, char **total_end)
{
if (!task->started) {
*total_start = *active_start = 0;
*total_end = *active_end = 0;
return;
}
jl_ptls_t ptls2 = task->ptls;
if (task->copy_stack && ptls2) {
*total_start = *active_start = (char*)ptls2->stackbase - ptls2->stacksize;
*total_end = *active_end = (char*)ptls2->stackbase;
}
else if (task->stkbuf) {
*total_start = *active_start = (char*)task->stkbuf;
#ifndef _OS_WINDOWS_
if (jl_all_tls_states[0]->root_task == task) {
// See jl_init_root_task(). The root task of the main thread
// has its buffer enlarged by an artificial 3000000 bytes, but
// that means that the start of the buffer usually points to
// inaccessible memory. We need to correct for this.
*active_start += ROOT_TASK_STACK_ADJUSTMENT;
*total_start += ROOT_TASK_STACK_ADJUSTMENT;
}
#endif
*total_end = *active_end = (char*)task->stkbuf + task->bufsz;
#ifdef COPY_STACKS
// save_stack stores the stack of an inactive task in stkbuf, and the
// actual number of used bytes in copy_stack.
if (task->copy_stack > 1)
*active_end = (char*)task->stkbuf + task->copy_stack;
#endif
}
else {
// no stack allocated yet
*total_start = *active_start = 0;
*total_end = *active_end = 0;
return;
}
if (task == jl_current_task) {
// scan up to current `sp` for current thread and task
*active_start = (char*)jl_get_frame_addr();
}
}
// Marked noinline so we can consistently skip the associated frame.
// `skip` is number of additional frames to skip.
NOINLINE static void record_backtrace(jl_ptls_t ptls, int skip) JL_NOTSAFEPOINT
{
// storing bt_size in ptls ensures roots in bt_data will be found
ptls->bt_size = rec_backtrace(ptls->bt_data, JL_MAX_BT_SIZE, skip + 1);
}
JL_DLLEXPORT void jl_set_next_task(jl_task_t *task) JL_NOTSAFEPOINT
{
jl_current_task->ptls->next_task = task;
}
JL_DLLEXPORT jl_task_t *jl_get_next_task(void) JL_NOTSAFEPOINT
{
jl_task_t *ct = jl_current_task;
if (ct->ptls->next_task)
return ct->ptls->next_task;
return ct;
}
#ifdef _COMPILER_TSAN_ENABLED_
const char tsan_state_corruption[] = "TSAN state corrupted. Exiting HARD!\n";
#endif
static void ctx_switch(jl_task_t *lastt)
{
jl_ptls_t ptls = lastt->ptls;
jl_task_t **pt = &ptls->next_task;
jl_task_t *t = *pt;
assert(t != lastt);
// none of these locks should be held across a task switch
assert(ptls->locks.len == 0);
#ifdef _COMPILER_TSAN_ENABLED_
if (lastt->ctx.tsan_state != __tsan_get_current_fiber()) {
// Something went really wrong - don't even assume that we can
// use assert/abort which involve lots of signal handling that
// looks at the tsan state.
write(STDERR_FILENO, tsan_state_corruption, sizeof(tsan_state_corruption) - 1);
_exit(1);
}
#endif
int killed = lastt->_state != JL_TASK_STATE_RUNNABLE;
if (!t->started && !t->copy_stack) {
// may need to allocate the stack
if (t->stkbuf == NULL) {
t->stkbuf = jl_alloc_fiber(&t->ctx, &t->bufsz, t);
if (t->stkbuf == NULL) {
#ifdef COPY_STACKS
// fall back to stack copying if mmap fails
t->copy_stack = 1;
t->sticky = 1;
t->bufsz = 0;
if (always_copy_stacks)
memcpy(&t->copy_stack_ctx, &ptls->copy_stack_ctx, sizeof(t->copy_stack_ctx));
else
memcpy(&t->ctx, &ptls->base_ctx, sizeof(t->ctx));
#else
jl_throw(jl_memory_exception);
#endif
}
}
}
if (killed) {
*pt = NULL; // can't fail after here: clear the gc-root for the target task now
lastt->gcstack = NULL;
if (!lastt->copy_stack && lastt->stkbuf) {
// early free of stkbuf back to the pool
jl_release_task_stack(ptls, lastt);
}
}
else {
#ifdef COPY_STACKS
if (lastt->copy_stack) { // save the old copy-stack
save_stack(ptls, lastt, pt); // allocates (gc-safepoint, and can also fail)
if (jl_setjmp(lastt->copy_stack_ctx.uc_mcontext, 0)) {
sanitizer_finish_switch_fiber();
// TODO: mutex unlock the thread we just switched from
return;
}
}
else
#endif
*pt = NULL; // can't fail after here: clear the gc-root for the target task now
lastt->ptls = NULL;
}
// set up global state for new task and clear global state for old task
t->ptls = ptls;
ptls->current_task = t;
JL_GC_PROMISE_ROOTED(t);
lastt->ptls = NULL;
#ifdef MIGRATE_TASKS
ptls->previous_task = lastt;
#endif
jl_set_pgcstack(&t->gcstack);
#if defined(_COMPILER_TSAN_ENABLED_)
tsan_switch_to_ctx(&t->tsan_state);
if (killed)
tsan_destroy_ctx(ptls, &lastt->tsan_state);
#endif
if (t->started) {
#ifdef COPY_STACKS
if (t->copy_stack) {
if (!killed && !lastt->copy_stack)
restore_stack2(t, ptls, lastt);
else if (lastt->copy_stack) {
restore_stack(t, ptls, NULL); // (doesn't return)
}
else {
restore_stack(t, ptls, (char*)1); // (doesn't return)
}
}
else
#endif
{
sanitizer_start_switch_fiber(t->stkbuf, t->bufsz);
if (killed) {
jl_set_fiber(&t->ctx); // (doesn't return)
abort(); // unreachable
}
else {
if (lastt->copy_stack) {
// Resume at the jl_setjmp earlier in this function,
// don't do a full task swap
jl_set_fiber(&t->ctx); // (doesn't return)
}
else {
jl_swap_fiber(&lastt->ctx, &t->ctx);
}
}
}
}
else {
sanitizer_start_switch_fiber(t->stkbuf, t->bufsz);
if (t->copy_stack && always_copy_stacks) {
#ifdef COPY_STACKS
#if defined(_OS_WINDOWS_)
jl_setcontext(&t->ctx);
#else
jl_longjmp(t->copy_stack_ctx.uc_mcontext, 1);
#endif
#endif
abort(); // unreachable
}
else {
if (killed) {
jl_start_fiber_set(&t->ctx); // (doesn't return)
abort();
}
else if (lastt->copy_stack) {
// Resume at the jl_setjmp earlier in this function
jl_start_fiber_set(&t->ctx); // (doesn't return)
abort();
}
else {
jl_start_fiber_swap(&lastt->ctx, &t->ctx);
}
}
}
sanitizer_finish_switch_fiber();
}
JL_DLLEXPORT void jl_switch(void)
{
jl_task_t *ct = jl_current_task;
jl_ptls_t ptls = ct->ptls;
jl_task_t *t = ptls->next_task;
if (t == ct) {
return;
}
if (t->started && t->stkbuf == NULL)
jl_error("attempt to switch to exited task");
if (ptls->in_finalizer)
jl_error("task switch not allowed from inside gc finalizer");
if (ptls->in_pure_callback)
jl_error("task switch not allowed from inside staged nor pure functions");
if (!jl_set_task_tid(t, ptls->tid)) // manually yielding to a task
jl_error("cannot switch to task running on another thread");
// Store old values on the stack and reset
sig_atomic_t defer_signal = ptls->defer_signal;
int8_t gc_state = jl_gc_unsafe_enter(ptls);
int finalizers_inhibited = ptls->finalizers_inhibited;
ptls->finalizers_inhibited = 0;
#ifdef ENABLE_TIMINGS
jl_timing_block_t *blk = ptls->timing_stack;
if (blk)
jl_timing_block_stop(blk);
ptls->timing_stack = NULL;
#endif
ctx_switch(ct);
#ifdef MIGRATE_TASKS
ptls = ct->ptls;
t = ptls->previous_task;
ptls->previous_task = NULL;
assert(t != ct);
assert(t->tid == ptls->tid);
if (!t->sticky && !t->copy_stack)
jl_atomic_store_release(&t->tid, -1);
#else
assert(ptls == ct->ptls);
#endif
// Pop old values back off the stack
assert(ct == jl_current_task &&
0 != ct->ptls &&
0 == ptls->finalizers_inhibited);
ptls->finalizers_inhibited = finalizers_inhibited;
#ifdef ENABLE_TIMINGS
assert(ptls->timing_stack == NULL);
ptls->timing_stack = blk;
if (blk)
jl_timing_block_start(blk);
#else
(void)ct;
#endif
jl_gc_unsafe_leave(ptls, gc_state);
sig_atomic_t other_defer_signal = ptls->defer_signal;
ptls->defer_signal = defer_signal;
if (other_defer_signal && !defer_signal)
jl_sigint_safepoint(ptls);
}
JL_DLLEXPORT void jl_switchto(jl_task_t **pt)
{
jl_set_next_task(*pt);
jl_switch();
}
JL_DLLEXPORT JL_NORETURN void jl_no_exc_handler(jl_value_t *e)
{
// NULL exception objects are used when rethrowing. we don't have a handler to process
// the exception stack, so at least report the exception at the top of the stack.
if (!e)
e = jl_current_exception();
jl_printf((JL_STREAM*)STDERR_FILENO, "fatal: error thrown and no exception handler available.\n");
jl_static_show((JL_STREAM*)STDERR_FILENO, e);
jl_printf((JL_STREAM*)STDERR_FILENO, "\n");
jlbacktrace(); // written to STDERR_FILENO
jl_exit(1);
}
// yield to exception handler
static void JL_NORETURN throw_internal(jl_task_t *ct, jl_value_t *exception JL_MAYBE_UNROOTED)
{
assert(!jl_get_safe_restore());
jl_ptls_t ptls = ct->ptls;
ptls->io_wait = 0;
// @time needs its compile timer disabled on error,
// and cannot use a try-finally as it would break scope for assignments
// We blindly disable compilation time tracking here, for all running Tasks, even though
// it may cause some incorrect measurements. This is a known bug, and is being tracked
// here: https://github.com/JuliaLang/julia/pull/39138
jl_atomic_store_relaxed(&jl_measure_compile_time_enabled, 0);
JL_GC_PUSH1(&exception);
jl_gc_unsafe_enter(ptls);
if (exception) {
// The temporary ptls->bt_data is rooted by special purpose code in the
// GC. This exists only for the purpose of preserving bt_data until we
// set ptls->bt_size=0 below.
jl_push_excstack(&ct->excstack, exception,
ptls->bt_data, ptls->bt_size);
ptls->bt_size = 0;
}
assert(ct->excstack && ct->excstack->top);
jl_handler_t *eh = ct->eh;
if (eh != NULL) {
#ifdef ENABLE_TIMINGS
jl_timing_block_t *cur_block = ptls->timing_stack;
while (cur_block && eh->timing_stack != cur_block) {
cur_block = jl_pop_timing_block(cur_block);
}
assert(cur_block == eh->timing_stack);
#endif
jl_longjmp(eh->eh_ctx, 1);
}
else {
jl_no_exc_handler(exception);
}
assert(0);
}
// record backtrace and raise an error
JL_DLLEXPORT void jl_throw(jl_value_t *e JL_MAYBE_UNROOTED)
{
assert(e != NULL);
jl_jmp_buf *safe_restore = jl_get_safe_restore();
if (safe_restore)
jl_longjmp(*safe_restore, 1);
jl_task_t *ct = jl_get_current_task();
if (ct == NULL) // During startup
jl_no_exc_handler(e);
JL_GC_PROMISE_ROOTED(ct);
record_backtrace(ct->ptls, 1);
throw_internal(ct, e);
}
// rethrow with current excstack state
JL_DLLEXPORT void jl_rethrow(void)
{
jl_task_t *ct = jl_current_task;
jl_excstack_t *excstack = ct->excstack;
if (!excstack || excstack->top == 0)
jl_error("rethrow() not allowed outside a catch block");
throw_internal(ct, NULL);
}
// Special case throw for errors detected inside signal handlers. This is not
// (cannot be) called directly in the signal handler itself, but is returned to
// after the signal handler exits.
JL_DLLEXPORT void JL_NORETURN jl_sig_throw(void)
{
CFI_NORETURN
jl_jmp_buf *safe_restore = jl_get_safe_restore();
if (safe_restore)
jl_longjmp(*safe_restore, 1);
jl_task_t *ct = jl_current_task;
jl_ptls_t ptls = ct->ptls;
jl_value_t *e = ptls->sig_exception;
ptls->sig_exception = NULL;
throw_internal(ct, e);
}
JL_DLLEXPORT void jl_rethrow_other(jl_value_t *e JL_MAYBE_UNROOTED)
{
// TODO: Should uses of `rethrow(exc)` be replaced with a normal throw, now
// that exception stacks allow root cause analysis?
jl_task_t *ct = jl_current_task;
jl_excstack_t *excstack = ct->excstack;
if (!excstack || excstack->top == 0)
jl_error("rethrow(exc) not allowed outside a catch block");
// overwrite exception on top of stack. see jl_excstack_exception
jl_excstack_raw(excstack)[excstack->top-1].jlvalue = e;
JL_GC_PROMISE_ROOTED(e);
throw_internal(ct, NULL);
}
/* This is xoshiro256++ 1.0, used for tasklocal random number generation in Julia.
This implementation is intended for embedders and internal use by the runtime, and is
based on the reference implementation at https://prng.di.unimi.it
Credits go to David Blackman and Sebastiano Vigna for coming up with this PRNG.
They described xoshiro256++ in "Scrambled Linear Pseudorandom Number Generators",
ACM Trans. Math. Softw., 2021.
There is a pure Julia implementation in stdlib that tends to be faster when used from
within Julia, due to inlining and more agressive architecture-specific optimizations.
*/
JL_DLLEXPORT uint64_t jl_tasklocal_genrandom(jl_task_t *task) JL_NOTSAFEPOINT
{
uint64_t s0 = task->rngState0;
uint64_t s1 = task->rngState1;
uint64_t s2 = task->rngState2;
uint64_t s3 = task->rngState3;
uint64_t t = s0 << 17;
uint64_t tmp = s0 + s3;
uint64_t res = ((tmp << 23) | (tmp >> 41)) + s0;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = (s3 << 45) | (s3 >> 19);
task->rngState0 = s0;
task->rngState1 = s1;
task->rngState2 = s2;
task->rngState3 = s3;
return res;
}
void rng_split(jl_task_t *from, jl_task_t *to) JL_NOTSAFEPOINT
{
/* TODO: consider a less ad-hoc construction
Ideally we could just use the output of the random stream to seed the initial
state of the child. Out of an overabundance of caution we multiply with
effectively random coefficients, to break possible self-interactions.
It is not the goal to mix bits -- we work under the assumption that the
source is well-seeded, and its output looks effectively random.
However, xoshiro has never been studied in the mode where we seed the
initial state with the output of another xoshiro instance.
Constants have nothing up their sleeve:
0x02011ce34bce797f == hash(UInt(1))|0x01
0x5a94851fb48a6e05 == hash(UInt(2))|0x01
0x3688cf5d48899fa7 == hash(UInt(3))|0x01
0x867b4bb4c42e5661 == hash(UInt(4))|0x01
*/
to->rngState0 = 0x02011ce34bce797f * jl_tasklocal_genrandom(from);
to->rngState1 = 0x5a94851fb48a6e05 * jl_tasklocal_genrandom(from);
to->rngState2 = 0x3688cf5d48899fa7 * jl_tasklocal_genrandom(from);
to->rngState3 = 0x867b4bb4c42e5661 * jl_tasklocal_genrandom(from);
}
JL_DLLEXPORT jl_task_t *jl_new_task(jl_function_t *start, jl_value_t *completion_future, size_t ssize)
{
jl_task_t *ct = jl_current_task;
jl_task_t *t = (jl_task_t*)jl_gc_alloc(ct->ptls, sizeof(jl_task_t), jl_task_type);
t->copy_stack = 0;
if (ssize == 0) {
// stack size unspecified; use default
if (always_copy_stacks) {
t->copy_stack = 1;
t->bufsz = 0;
}
else {
t->bufsz = JL_STACK_SIZE;
}
t->stkbuf = NULL;
}
else {
// user requested dedicated stack of a certain size
if (ssize < MINSTKSZ)
ssize = MINSTKSZ;
t->bufsz = ssize;
t->stkbuf = jl_alloc_fiber(&t->ctx, &t->bufsz, t);
if (t->stkbuf == NULL)
jl_throw(jl_memory_exception);
}
t->next = jl_nothing;
t->queue = jl_nothing;
t->tls = jl_nothing;
t->_state = JL_TASK_STATE_RUNNABLE;
t->start = start;
t->result = jl_nothing;
t->donenotify = completion_future;
t->_isexception = 0;
// Inherit logger state from parent task
t->logstate = ct->logstate;
// Fork task-local random state from parent
rng_split(ct, t);
// there is no active exception handler available on this stack yet
t->eh = NULL;
t->sticky = 1;
t->gcstack = NULL;
t->excstack = NULL;
t->started = 0;
t->prio = -1;
t->tid = t->copy_stack ? ct->tid : -1; // copy_stacks are always pinned since they can't be moved
t->ptls = NULL;
t->world_age = 0;
#ifdef COPY_STACKS
if (!t->copy_stack) {
#if defined(JL_DEBUG_BUILD)
memset(&t->ctx, 0, sizeof(t->ctx));
#endif
}
else {
if (always_copy_stacks)
memcpy(&t->copy_stack_ctx, &ct->ptls->copy_stack_ctx, sizeof(t->copy_stack_ctx));
else
memcpy(&t->ctx, &ct->ptls->base_ctx, sizeof(t->ctx));
}
#endif
#ifdef _COMPILER_TSAN_ENABLED_
t->tsan_state = __tsan_create_fiber(0);
#endif
return t;
}
// a version of jl_current_task safe for unmanaged threads
JL_DLLEXPORT jl_task_t *jl_get_current_task(void)
{
jl_gcframe_t **pgcstack = jl_get_pgcstack();
return pgcstack == NULL ? NULL : container_of(pgcstack, jl_task_t, gcstack);
}
#ifdef JL_HAVE_ASYNCIFY
JL_DLLEXPORT jl_ucontext_t *task_ctx_ptr(jl_task_t *t)
{
return &t->ctx;
}
JL_DLLEXPORT jl_value_t *jl_get_root_task(void)
{
jl_task_t *ct = jl_current_task;
return (jl_value_t*)ct->ptls->root_task;
}
JL_DLLEXPORT void jl_task_wait()
{
static jl_function_t *wait_func = NULL;
if (!wait_func) {
wait_func = (jl_function_t*)jl_get_global(jl_base_module, jl_symbol("wait"));
}
jl_task_t *ct = jl_current_task;
size_t last_age = ct->world_age;
ct->world_age = jl_get_world_counter();
jl_apply(&wait_func, 1);
ct->world_age = last_age;
}
JL_DLLEXPORT void jl_schedule_task(jl_task_t *task)
{
static jl_function_t *sched_func = NULL;
if (!sched_func) {
sched_func = (jl_function_t*)jl_get_global(jl_base_module, jl_symbol("schedule"));
}
jl_task_t *ct = jl_current_task;
size_t last_age = ct->world_age;
ct->world_age = jl_get_world_counter();
jl_value_t *args[] = {(jl_value_t*)sched_func, (jl_value_t*)task};
jl_apply(args, 2);
ct->world_age = last_age;
}
#endif
// Do one-time initializations for task system
void jl_init_tasks(void) JL_GC_DISABLED
{
char *acs = getenv("JULIA_COPY_STACKS");
if (acs) {
if (!strcmp(acs, "1") || !strcmp(acs, "yes"))
always_copy_stacks = 1;
else if (!strcmp(acs, "0") || !strcmp(acs, "no"))
always_copy_stacks = 0;
else {
jl_safe_printf("invalid JULIA_COPY_STACKS value: %s\n", acs);
exit(1);
}
}
#ifndef COPY_STACKS
if (always_copy_stacks) {
jl_safe_printf("Julia built without COPY_STACKS support");
exit(1);
}
#endif
}
STATIC_OR_JS void NOINLINE JL_NORETURN start_task(void)
{
CFI_NORETURN
// this runs the first time we switch to a task
sanitizer_finish_switch_fiber();
#ifdef __clang_analyzer__
jl_task_t *ct = jl_get_current_task();
JL_GC_PROMISE_ROOTED(ct);
#else
jl_task_t *ct = jl_current_task;
#endif
jl_ptls_t ptls = ct->ptls;
jl_value_t *res;
assert(ptls->finalizers_inhibited == 0);
#ifdef MIGRATE_TASKS
jl_task_t *pt = ptls->previous_task;
ptls->previous_task = NULL;
if (!pt->sticky && !pt->copy_stack)
jl_atomic_store_release(&pt->tid, -1);
#endif
ct->started = 1;
if (ct->_isexception) {
record_backtrace(ptls, 0);
jl_push_excstack(&ct->excstack, ct->result,
ptls->bt_data, ptls->bt_size);
res = ct->result;
}
else {
JL_TRY {
if (ptls->defer_signal) {
ptls->defer_signal = 0;
jl_sigint_safepoint(ptls);
}
JL_TIMING(ROOT);
ct->world_age = jl_world_counter;
res = jl_apply(&ct->start, 1);
}
JL_CATCH {
res = jl_current_exception();
ct->_isexception = 1;
goto skip_pop_exception;
}
skip_pop_exception:;
}
ct->result = res;
jl_gc_wb(ct, ct->result);
jl_finish_task(ct);
gc_debug_critical_error();
abort();
}
#if defined(JL_HAVE_UCONTEXT)
#ifdef _OS_WINDOWS_
#define setcontext jl_setcontext
#define swapcontext jl_swapcontext
#define makecontext jl_makecontext
#endif
static char *jl_alloc_fiber(jl_ucontext_t *t, size_t *ssize, jl_task_t *owner) JL_NOTSAFEPOINT
{
#ifndef _OS_WINDOWS_
int r = getcontext(t);
if (r != 0)
jl_error("getcontext failed");
#endif
void *stk = jl_malloc_stack(ssize, owner);
if (stk == NULL)
return NULL;
t->uc_stack.ss_sp = stk;
t->uc_stack.ss_size = *ssize;
#ifdef _OS_WINDOWS_
makecontext(t, &start_task);
#else
t->uc_link = NULL;
makecontext(t, &start_task, 0);
#endif
return (char*)stk;
}
static void jl_start_fiber_set(jl_ucontext_t *t)
{
setcontext(t);
}
static void jl_start_fiber_swap(jl_ucontext_t *lastt, jl_ucontext_t *t)
{
assert(lastt);
swapcontext(lastt, t);
}
static void jl_swap_fiber(jl_ucontext_t *lastt, jl_ucontext_t *t)
{
swapcontext(lastt, t);
}
static void jl_set_fiber(jl_ucontext_t *t)
{
setcontext(t);
}
#endif
#if defined(JL_HAVE_UNW_CONTEXT) || defined(JL_HAVE_ASM)
static char *jl_alloc_fiber(jl_ucontext_t *t, size_t *ssize, jl_task_t *owner)
{
char *stkbuf = (char*)jl_malloc_stack(ssize, owner);
if (stkbuf == NULL)
return NULL;
#ifndef __clang_analyzer__
((char**)t)[0] = stkbuf; // stash the stack pointer somewhere for start_fiber
((size_t*)t)[1] = *ssize; // stash the stack size somewhere for start_fiber
#endif
return stkbuf;
}
#endif
#if defined(JL_HAVE_UNW_CONTEXT)
static inline void jl_unw_swapcontext(unw_context_t *old, unw_cursor_t *c)
{
volatile int returns = 0;
int r = unw_getcontext(old);
if (++returns == 2) // r is garbage after the first return
return;
if (r != 0 || returns != 1)
abort();
unw_resume(c);
}
static void jl_swap_fiber(jl_ucontext_t *lastt, jl_ucontext_t *t)
{
unw_cursor_t c;
int r = unw_init_local(&c, t);
if (r < 0)
abort();
jl_unw_swapcontext(lastt, &c);
}
static void jl_set_fiber(unw_context_t *t)
{
unw_cursor_t c;
int r = unw_init_local(&c, t);
if (r < 0)
abort();
unw_resume(&c);
}
#elif defined(JL_HAVE_ASM)
static void jl_swap_fiber(jl_ucontext_t *lastt, jl_ucontext_t *t)
{
if (jl_setjmp(lastt->uc_mcontext, 0))
return;
jl_set_fiber(t); // doesn't return
}
static void jl_set_fiber(jl_ucontext_t *t)
{
jl_longjmp(t->uc_mcontext, 1);
}
#endif
#if defined(JL_HAVE_UNW_CONTEXT) && !defined(JL_HAVE_ASM)