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
//! This file contains the low level operations that deal with switching between
//! stacks.
//!
//! The core operations are:
//! - `init_stack` to initialize a stack for the first resume.
//! - `switch_and_link` to switch control into a coroutine.
//! - `switch_yield` to return control from a coroutine back to its parent.
//! - `switch_and_reset` to return control for the last time.
//!
//! ## Linked stacks
//!
//! Stack linking allows a context switch to be automatically performed when the
//! initial function of a context returns or unwinds. This works by stashing a
//! copy of the parent context stack pointer near the stack base and updating it
//! every time we switch into the child context using `switch_and_link`.
//!
//! For unwinding and backtraces to work as expected (that is, to continue in
//! the parent after unwinding past the initial function of a child context),
//! we need to use special DWARF CFI instructions to tell the unwinder how to
//! find the parent frame.
//!
//! If you're curious a decent introduction to CFI things and unwinding is at
//! <https://www.imperialviolet.org/2017/01/18/cfi.html>.
//!
//! ## Frame pointers
//!
//! Some tools or OSes do not use DWARF for stack unwinding, preferring to use
//! the older (but simpler) frame pointer chain to capture a backtrace. This is
//! particularly common in performance profiling tools such as Linux's perf
//! callgraph profiler. These work by following a linked list of frame records
//! starting from the RBP register. Each record consists of 2 words: a pointer
//! to the previous frame (aka the previous RBP value) and the return address
//! for this frame (aka the saved RIP value).
//!
//! To support these tools, we also generate a valid stack frame record when
//! switching into a coroutine. This works by treating the parent link at the
//! root of the stack as a frame record which points to the top of the parent
//! stack. The top of the parent stack contains the saved RBP and RIP values in
//! the correct format for a frame record, which allows unwinding to continue on
//! the parent stack.
//!
//! The RIP value associated with the parent link is invalid since it points to
//! the start of the initial function, but this shouldn't block the unwinding
//! process.
//!
//! ## Stack layout
//!
//! Here is what the layout of the stack looks like when a coroutine is
//! suspended.
//!
//! ```text
//! +--------------+ <- Stack base
//! | Initial func | <- Only used once when resuming for the first time.
//! +--------------+
//! | Parent link | <- The Yielder is a pointer to this address. When the
//! +--------------+ coroutine is running, it points to the top of the
//! | | parent stack which contains a saved RIP, RBP and RBX
//! ~ ... ~ just like a suspended coroutine.
//! | |
//! +--------------+
//! | Saved RBP |
//! +--------------+
//! | Saved RBX |
//! +--------------+
//! | Saved RIP |
//! +--------------+
//! ```
//!
//! And this is the layout of the parent stack when a coroutine is running:
//!
//! ```text
//! | |
//! ~ ... ~
//! | |
//! +----------------+
//! | Saved RBX |
//! +----------------+
//! | Saved RIP | <- These 2 values form a valid entry in the frame pointer
//! +----------------+ | chain. The parent link itself is another entry in the
//! | Saved RBP | <- frame pointer chain since RBP points to it.
//! +----------------+ <- Parent link points here.
//! ```
//!
//! On UEFI targets, a secondary copy of the saved RIP is added below the saved
//! RBX. This is needed because SEH unwind codes are not as flexible as DWARF
//! CFI and the unwinder always pops a return address after processing all
//! unwind opcodes.
//!
//! ```text
//! | |
//! ~ ... ~
//! | |
//! +----------------+
//! | Secondary RIP | <- Only on UEFI; used by the SEH unwinder.
//! +----------------+
//! | Saved RBX |
//! +----------------+
//! | Saved RIP |
//! +----------------+
//! | Saved RBP |
//! +----------------+ <- Parent link points here.
//! ```
//!
//! And finally, this is the stack layout of a coroutine that has just been
//! initialized:
//!
//! ```text
//! +--------------+ <- Stack base
//! | Initial func |
//! +--------------+
//! | Parent link | <- This hasn't been filled in yet at this point.
//! +--------------+
//! | |
//! ~ Initial obj ~ <- This has an unknown size, but the size is rounded up to
//! | | `STACK_ALIGNMENT`.
//! +--------------+
//! | Initial RIP | <- Points to stack_init_trampoline
//! +--------------+ <- Initial stack pointer
//! ```
use ;
use ;
use crateadjusted_stack_base;
use crate;
use crate;
use crateEncodedValue;
// On UEFI targets, we emit SEH unwind information so that PE/COFF debuggers
// (WinDbg, LLDB) can reconstruct backtraces across coroutine stack boundaries.
// Unlike Windows, UEFI does not have a Thread Environment Block (TEB), so the
// SEH annotations are simpler with adjusted stack offsets.
//
// The cfi!() and seh!() macros ensure that DWARF CFI and SEH directives are
// mutually exclusive: UEFI uses SEH (.pdata/.xdata), all other platforms use
// DWARF CFI (.eh_frame).
cfg_if!
pub const STACK_ALIGNMENT: usize = 16;
pub const PARENT_STACK_OFFSET: usize = 0;
pub const PARENT_LINK_OFFSET: usize = 16;
pub type StackWord = u64;
// This is a pretty special function that has no real signature. Its use is to
// be the "base" function of all coroutines. This entrypoint is used in
// init_stack() to bootstrap the execution of a new coroutine.
//
// We also use this function as a persistent frame on the stack to emit unwind
// information to unwind into the caller. This allows us to unwind from the
// coroutines's stack back to the main stack that the coroutine was called from.
// We use special directives here to do so since this is a pretty nonstandard
// function.
//
// On non-UEFI platforms we use DWARF CFI directives. On UEFI we use SEH
// directives instead (see the seh!() and cfi!() macros above).
global_asm!;
// This function calls a function pointer on a new stack and restores the
// original stack upon returning. It is used by on_stack() and is much simpler
// than the full coroutine logic, but also more limited since yielding is not
// possible.
global_asm!;
// These trampolines use a custom calling convention and should only be called
// with inline assembly.
extern "C"
/// Sets up the initial state on a stack so that the given function is
/// executed on the first switch to this stack.
///
/// The given object is written to the stack and its address on the stack is
/// passed as the 3rd argument to the initial function.
pub unsafe
/// This function is used to transfer control to a coroutine along with an
/// argument. A pointer back to our context is stored at a fixed offset from
/// the base of the target stack.
///
/// When another context switches back to us, we receive the argument they sent
/// as well as the stack pointer of the originating context. This can be `None`
/// if the caller used `switch_and_reset` and can't be returned to.
pub unsafe
/// This function performs the inverse of `switch_and_link` by returning
/// control to the parent context.
///
/// This function does not return a stack pointer value for the parent context
/// when it switches back to us. Instead, the stack pointer value for the parent
/// context is available in the parent link on the stack.
// This function must always be inlined because it is very sensitive to the
// CPU's return address predictor. See stack_init_trampoline for more details.
pub unsafe
/// Variant of `switch_yield` used when returning from the initial function in a
/// context.
///
/// This works by returning a stack pointer value of 0 which prevents the
/// current context from being resumed. There must not be any object left on the
/// stack with pending destructors when this is called.
///
/// Since the stack is still available at this point, `arg` can safely point to
/// memory on the stack until the parent context frees or reuses the stack.
// This function must always be inlined because it is very sensitive to the
// CPU's return address predictor. See stack_init_trampoline for more details.
pub unsafe !
/// Variant of `switch_and_link` which runs a function on the coroutine stack
/// instead of resuming the coroutine. This function will throw an exception
/// which will unwind the coroutine stack to its root.
pub unsafe
/// Drops the initial object on a coroutine that has not started yet.
pub unsafe
/// Registers which must be updated upon return from a trap handler.
///
/// The exact set of registers that need to be updated varies depending on the
/// target. Note that *all* registers must be updated to the specified values,
/// otherwise behavior is undefined.
///
/// To catch any issues at compilation time, it is recommended to use Rust's
/// pattern matching syntax to extract the individual registers from this
/// struct.
///
/// ```
/// # use corosensei::trap::TrapHandlerRegs;
/// # let regs = TrapHandlerRegs { rip: 0, rsp: 0, rbp: 0, rdi: 0, rsi: 0 };
/// let TrapHandlerRegs { rip, rsp, rbp, rdi, rsi } = regs;
/// ```
/// This function sets up the stack and register state of a trap handler so that
/// upon resuming execution control will immediately jump to the given function
/// with the given argument.
pub unsafe
/// This function executes a function on the given stack. The argument is passed
/// through to the called function.
pub unsafe