This repository was archived by the owner on Mar 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathinstance.rs
More file actions
1613 lines (1438 loc) · 63 KB
/
instance.rs
File metadata and controls
1613 lines (1438 loc) · 63 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
pub mod execution;
mod siginfo_ext;
pub mod signals;
pub mod state;
pub use crate::instance::execution::{KillError, KillState, KillSuccess, KillSwitch};
pub use crate::instance::signals::{signal_handler_none, SignalBehavior, SignalHandler};
pub use crate::instance::state::State;
use crate::alloc::Alloc;
use crate::context::Context;
use crate::embed_ctx::CtxMap;
use crate::error::Error;
#[cfg(feature = "concurrent_testpoints")]
use crate::lock_testpoints::LockTestpoints;
use crate::module::{self, FunctionHandle, Global, GlobalValue, Module, TrapCode};
use crate::region::RegionInternal;
use crate::sysdeps::HOST_PAGE_SIZE_EXPECTED;
use crate::val::{UntypedRetVal, Val};
use crate::WASM_PAGE_SIZE;
use libc::{c_void, pthread_self, siginfo_t, uintptr_t};
use lucet_module::InstanceRuntimeData;
use memoffset::offset_of;
use std::any::Any;
use std::cell::{BorrowError, BorrowMutError, Ref, RefCell, RefMut, UnsafeCell};
use std::convert::TryFrom;
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, NonNull};
use std::sync::Arc;
pub const LUCET_INSTANCE_MAGIC: u64 = 746_932_922;
thread_local! {
/// The host context.
///
/// Control returns here implicitly due to the setup in `Context::init()` when guest functions
/// return normally. Control can return here explicitly from signal handlers when the guest
/// program needs to be terminated.
///
/// This is an `UnsafeCell` due to nested borrows. The context must be borrowed mutably when
/// swapping to the guest context, which means that borrow exists for the entire time the guest
/// function runs even though the mutation to the host context is done only at the beginning of
/// the swap. Meanwhile, the signal handler can run at any point during the guest function, and
/// so it also must be able to immutably borrow the host context if it needs to swap back. The
/// runtime borrowing constraints for a `RefCell` are therefore too strict for this variable.
pub(crate) static HOST_CTX: UnsafeCell<Context> = UnsafeCell::new(Context::new());
/// The currently-running `Instance`, if one exists.
pub(crate) static CURRENT_INSTANCE: RefCell<Option<NonNull<Instance>>> = RefCell::new(None);
}
/// A smart pointer to an [`Instance`](struct.Instance.html) that properly manages cleanup when dropped.
///
/// Instances are always stored in memory backed by a `Region`; we never want to create one directly
/// with the Rust allocator. This type allows us to abide by that rule while also having an owned
/// type that cleans up the instance when we are done with it.
///
/// Since this type implements `Deref` and `DerefMut` to `Instance`, it can usually be treated as
/// though it were a `&mut Instance`.
pub struct InstanceHandle {
inst: NonNull<Instance>,
needs_inst_drop: bool,
}
// raw pointer lint
unsafe impl Send for InstanceHandle {}
/// Create a new `InstanceHandle`.
///
/// This is not meant for public consumption, but rather is used to make implementations of
/// `Region`.
pub fn new_instance_handle(
instance: *mut Instance,
module: Arc<dyn Module>,
alloc: Alloc,
embed_ctx: CtxMap,
) -> Result<InstanceHandle, Error> {
let inst = NonNull::new(instance)
.ok_or_else(|| lucet_format_err!("instance pointer is null; this is a bug"))?;
lucet_ensure!(
unsafe { inst.as_ref().magic } != LUCET_INSTANCE_MAGIC,
"created a new instance handle in memory with existing instance magic; this is a bug"
);
let mut handle = InstanceHandle {
inst,
needs_inst_drop: false,
};
let inst = Instance::new(alloc, module, embed_ctx);
unsafe {
// this is wildly unsafe! you must be very careful to not let the drop impls run on the
// uninitialized fields; see
// <https://doc.rust-lang.org/std/mem/fn.forget.html#use-case-1>
// write the whole struct into place over the uninitialized page
ptr::write(&mut *handle, inst);
};
handle.needs_inst_drop = true;
handle.reset()?;
Ok(handle)
}
pub fn instance_handle_to_raw(mut inst: InstanceHandle) -> *mut Instance {
inst.needs_inst_drop = false;
inst.inst.as_ptr()
}
pub unsafe fn instance_handle_from_raw(
ptr: *mut Instance,
needs_inst_drop: bool,
) -> InstanceHandle {
InstanceHandle {
inst: NonNull::new_unchecked(ptr),
needs_inst_drop,
}
}
// Safety argument for these deref impls: the instance's `Alloc` field contains an `Arc` to the
// region that backs this memory, keeping the page containing the `Instance` alive as long as the
// region exists
impl Deref for InstanceHandle {
type Target = Instance;
fn deref(&self) -> &Self::Target {
unsafe { self.inst.as_ref() }
}
}
impl DerefMut for InstanceHandle {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.inst.as_mut() }
}
}
impl Drop for InstanceHandle {
fn drop(&mut self) {
if self.needs_inst_drop {
unsafe {
let inst = self.inst.as_mut();
// Grab a handle to the region to ensure it outlives `inst`.
//
// This ensures that the region won't be dropped by `inst` being
// dropped, which could result in `inst` being unmapped by the
// Region *during* drop of the Instance's fields.
let region: Arc<dyn RegionInternal> = inst.alloc().region.clone();
// drop the actual instance
std::ptr::drop_in_place(inst);
// and now we can drop what may be the last Arc<Region>. If it is
// it can safely do what it needs with memory; we're not running
// destructors on it anymore.
mem::drop(region);
}
}
}
}
/// A Lucet program, together with its dedicated memory and signal handlers.
///
/// This is the primary interface for running programs, examining return values, and accessing the
/// WebAssembly heap.
///
/// `Instance`s are never created by runtime users directly, but rather are acquired from
/// [`Region`](../region/trait.Region.html)s and often accessed through
/// [`InstanceHandle`](../instance/struct.InstanceHandle.html) smart pointers. This guarantees that instances
/// and their fields are never moved in memory, otherwise raw pointers in the metadata could be
/// unsafely invalidated.
///
/// An instance occupies one 4096-byte page in memory, with a layout like:
/// ```text
/// 0xXXXXX000:
/// Instance {
/// .magic
/// .embed_ctx
/// ... etc ...
/// }
///
/// // unused space
///
/// InstanceInternals {
/// .globals
/// .instruction_counter
/// } // last address *inside* `InstanceInternals` is 0xXXXXXFFF
/// 0xXXXXY000: // start of next page, VMContext points here
/// Heap {
/// ..
/// }
/// ```
///
/// This layout allows modules to tightly couple to a handful of fields related to the instance,
/// rather than possibly requiring compiler-side changes (and recompiles) whenever `Instance`
/// changes.
///
/// It also obligates `Instance` to be immediately followed by the heap, but otherwise leaves the
/// locations of the stack, globals, and any other data, to be implementation-defined by the
/// `Region` that actually creates `Slot`s onto which `Instance` are mapped.
/// For information about the layout of all instance-related memory, see the documentation of
/// [MmapRegion](../region/mmap/struct.MmapRegion.html).
#[repr(C)]
#[repr(align(4096))]
pub struct Instance {
/// Used to catch bugs in pointer math used to find the address of the instance
magic: u64,
/// The embedding context is a map containing embedder-specific values that are used to
/// implement hostcalls
pub(crate) embed_ctx: CtxMap,
/// The program (WebAssembly module) that is the entrypoint for the instance.
pub(crate) module: Arc<dyn Module>,
/// The `Context` in which the guest program runs
pub(crate) ctx: Context,
/// Instance state and error information
pub(crate) state: State,
/// Small mutexed state used for remote kill switch functionality
pub(crate) kill_state: Arc<KillState>,
#[cfg(feature = "concurrent_testpoints")]
/// Conditionally-present helpers to force permutations of possible races in testing.
pub lock_testpoints: Arc<LockTestpoints>,
/// The memory allocated for this instance
alloc: Alloc,
/// Handler run for signals that do not arise from a known WebAssembly trap, or that involve
/// memory outside of the current instance.
fatal_handler: fn(&Instance) -> !,
/// A fatal handler set from C
c_fatal_handler: Option<unsafe extern "C" fn(*mut Instance)>,
/// Handler run when `SIGBUS`, `SIGFPE`, `SIGILL`, or `SIGSEGV` are caught by the instance thread.
signal_handler: Box<
dyn Fn(
&Instance,
&Option<TrapCode>,
libc::c_int,
*const siginfo_t,
*const c_void,
) -> SignalBehavior,
>,
/// Whether to ensure the Lucet signal handler is installed when running this instance.
ensure_signal_handler_installed: bool,
/// Whether to install an alternate signal stack while the instance is running.
ensure_sigstack_installed: bool,
/// Pointer to the function used as the entrypoint.
entrypoint: Option<FunctionHandle>,
/// The value passed back to the guest when resuming a yielded instance.
pub(crate) resumed_val: Option<Box<dyn Any + 'static>>,
/// Whether to terminate the guest when `memory.grow` fails, rather than returning `-1`;
/// disabled by default.
///
/// This behavior deviates from the WebAssembly spec, but is useful in practice for determining
/// when guest programs fail due to an exhausted heap.
///
/// Most languages will compile to code that includes an `unreachable` instruction if allocation
/// fails, but this same instruction might also appear when other types of assertions fail,
/// `panic!()` is called, etc. Terminating allows the error to be more directly identifiable.
terminate_on_heap_oom: bool,
/// `_padding` must be the last member of the structure.
/// This marks where the padding starts to make the structure exactly 4096 bytes long.
/// It is also used to compute the size of the structure up to that point, i.e. without padding.
_padding: (),
}
/// Users of `Instance` must be very careful about when instances are dropped!
///
/// Typically you will not have to worry about this, as InstanceHandle will robustly handle
/// Instance drop semantics. If an instance is dropped, and the Region it's in has already dropped,
/// it may contain the last reference counted pointer to its Region. If so, when Instance's
/// destructor runs, Region will be dropped, and may free or otherwise invalidate the memory that
/// this Instance exists in, *while* the Instance destructor is executing.
impl Drop for Instance {
fn drop(&mut self) {
// Reset magic to indicate this instance
// is no longer valid
self.magic = 0;
}
}
/// The result of running or resuming an [`Instance`](struct.Instance.html).
#[derive(Debug)]
pub enum RunResult {
/// An instance returned with a value.
///
/// The actual type of the contained value depends on the return type of the guest function that
/// was called. For guest functions with no return value, it is undefined behavior to do
/// anything with this value.
Returned(UntypedRetVal),
/// An instance yielded, potentially with a value.
///
/// This arises when a hostcall invokes one of the
/// [`Vmctx::yield_*()`](vmctx/struct.Vmctx.html#method.yield_) family of methods. Depending on which
/// variant is used, the `YieldedVal` may contain a value passed from the guest context to the
/// host.
///
/// An instance that has yielded may only be resumed
/// ([with](struct.Instance.html#method.resume_with_val) or
/// [without](struct.Instance.html#method.resume) a value to returned to the guest),
/// [reset](struct.Instance.html#method.reset), or dropped. Attempting to run an instance from a
/// new entrypoint after it has yielded but without first resetting will result in an error.
Yielded(YieldedVal),
}
impl RunResult {
/// Try to get a return value from a run result, returning `Error::InstanceNotReturned` if the
/// instance instead yielded.
pub fn returned(self) -> Result<UntypedRetVal, Error> {
match self {
RunResult::Returned(rv) => Ok(rv),
RunResult::Yielded(_) => Err(Error::InstanceNotReturned),
}
}
/// Try to get a reference to a return value from a run result, returning
/// `Error::InstanceNotReturned` if the instance instead yielded.
pub fn returned_ref(&self) -> Result<&UntypedRetVal, Error> {
match self {
RunResult::Returned(rv) => Ok(rv),
RunResult::Yielded(_) => Err(Error::InstanceNotReturned),
}
}
/// Returns `true` if the instance returned a value.
pub fn is_returned(&self) -> bool {
self.returned_ref().is_ok()
}
/// Unwraps a run result into a return value.
///
/// # Panics
///
/// Panics if the instance instead yielded, with a panic message including the passed message.
pub fn expect_returned(self, msg: &str) -> UntypedRetVal {
self.returned().expect(msg)
}
/// Unwraps a run result into a returned value.
///
/// # Panics
///
/// Panics if the instance instead yielded.
pub fn unwrap_returned(self) -> UntypedRetVal {
self.returned().unwrap()
}
/// Try to get a yielded value from a run result, returning `Error::InstanceNotYielded` if the
/// instance instead returned.
pub fn yielded(self) -> Result<YieldedVal, Error> {
match self {
RunResult::Returned(_) => Err(Error::InstanceNotYielded),
RunResult::Yielded(yv) => Ok(yv),
}
}
/// Try to get a reference to a yielded value from a run result, returning
/// `Error::InstanceNotYielded` if the instance instead returned.
pub fn yielded_ref(&self) -> Result<&YieldedVal, Error> {
match self {
RunResult::Returned(_) => Err(Error::InstanceNotYielded),
RunResult::Yielded(yv) => Ok(yv),
}
}
/// Returns `true` if the instance yielded.
pub fn is_yielded(&self) -> bool {
self.yielded_ref().is_ok()
}
/// Returns `true` if the instance can be resumed: either it has yielded, or its bound has
/// expired.
pub fn can_resume(&self) -> bool {
self.is_yielded()
}
/// Returns `true` if the instance has yielded a value of the given type.
pub fn has_yielded<A: Any>(&self) -> bool {
match self {
RunResult::Yielded(yv) => yv.is::<A>(),
_ => false,
}
}
/// Unwraps a run result into a yielded value.
///
/// # Panics
///
/// Panics if the instance instead returned, with a panic message including the passed message.
pub fn expect_yielded(self, msg: &str) -> YieldedVal {
self.yielded().expect(msg)
}
/// Unwraps a run result into a yielded value.
///
/// # Panics
///
/// Panics if the instance instead returned.
pub fn unwrap_yielded(self) -> YieldedVal {
self.yielded().unwrap()
}
}
/// An "internal" run result: either a `RunResult` or a bound expiration. We do not expose bound
/// expirations to the caller directly; rather, we only handle them in `run_async()`.
pub(crate) enum InternalRunResult {
Normal(RunResult),
BoundExpired,
}
impl InternalRunResult {
pub(crate) fn unwrap(self) -> RunResult {
match self {
InternalRunResult::Normal(result) => result,
InternalRunResult::BoundExpired => panic!("should not have had a runtime bound"),
}
}
}
impl std::convert::Into<InternalRunResult> for RunResult {
fn into(self) -> InternalRunResult {
InternalRunResult::Normal(self)
}
}
/// APIs that are internal, but useful to implementors of extension modules; you probably don't want
/// this trait!
///
/// This is a trait rather than inherent `impl`s in order to keep the `lucet-runtime` API clean and
/// safe.
pub trait InstanceInternal {
fn alloc(&self) -> &Alloc;
fn alloc_mut(&mut self) -> &mut Alloc;
fn module(&self) -> &dyn Module;
fn state(&self) -> &State;
fn valid_magic(&self) -> bool;
}
impl InstanceInternal for Instance {
/// Get a reference to the instance's `Alloc`.
fn alloc(&self) -> &Alloc {
&self.alloc
}
/// Get a mutable reference to the instance's `Alloc`.
fn alloc_mut(&mut self) -> &mut Alloc {
&mut self.alloc
}
/// Get a reference to the instance's `Module`.
fn module(&self) -> &dyn Module {
self.module.deref()
}
/// Get a reference to the instance's `State`.
fn state(&self) -> &State {
&self.state
}
/// Check whether the instance magic is valid.
fn valid_magic(&self) -> bool {
self.magic == LUCET_INSTANCE_MAGIC
}
}
// Public API
impl Instance {
/// Run a function with arguments in the guest context at the given entrypoint.
///
/// ```no_run
/// # use lucet_runtime_internals::instance::InstanceHandle;
/// # let instance: InstanceHandle = unimplemented!();
/// // regular execution yields `Ok(UntypedRetVal)`
/// let retval = instance.run("factorial", &[5u64.into()]).unwrap().unwrap_returned();
/// assert_eq!(u64::from(retval), 120u64);
///
/// // runtime faults yield `Err(Error)`
/// let result = instance.run("faulting_function", &[]);
/// assert!(result.is_err());
/// ```
///
/// # Safety
///
/// This is unsafe in two ways:
///
/// - The type of the entrypoint might not be correct. It might take a different number or
/// different types of arguments than are provided to `args`. It might not even point to a
/// function! We will likely add type information to `lucetc` output so we can dynamically check
/// the type in the future.
///
/// - The entrypoint is foreign code. While we may be convinced that WebAssembly compiled to
/// native code by `lucetc` is safe, we do not have the same guarantee for the hostcalls that a
/// guest may invoke. They might be implemented in an unsafe language, so we must treat this
/// call as unsafe, just like any other FFI call.
///
/// For the moment, we do not mark this as `unsafe` in the Rust type system, but that may change
/// in the future.
pub fn run(&mut self, entrypoint: &str, args: &[Val]) -> Result<RunResult, Error> {
let func = self.module.get_export_func(entrypoint)?;
Ok(self.run_func(func, &args, false, None)?.unwrap())
}
/// Run a function with arguments in the guest context from the [WebAssembly function
/// table](https://webassembly.github.io/spec/core/syntax/modules.html#tables).
///
/// # Safety
///
/// The same safety caveats of [`Instance::run()`](struct.Instance.html#method.run) apply.
pub fn run_func_idx(
&mut self,
table_idx: u32,
func_idx: u32,
args: &[Val],
) -> Result<RunResult, Error> {
let func = self.module.get_func_from_idx(table_idx, func_idx)?;
Ok(self.run_func(func, &args, false, None)?.unwrap())
}
/// Resume execution of an instance that has yielded without providing a value to the guest.
///
/// This should only be used when the guest yielded with
/// [`Vmctx::yield_()`](vmctx/struct.Vmctx.html#method.yield_) or
/// [`Vmctx::yield_val()`](vmctx/struct.Vmctx.html#method.yield_val).
///
/// # Safety
///
/// The foreign code safety caveat of [`Instance::run()`](struct.Instance.html#method.run)
/// applies.
pub fn resume(&mut self) -> Result<RunResult, Error> {
self.resume_with_val(EmptyYieldVal)
}
/// Resume execution of an instance that has yielded, providing a value to the guest.
///
/// The type of the provided value must match the type expected by
/// [`Vmctx::yield_expecting_val()`](vmctx/struct.Vmctx.html#method.yield_expecting_val) or
/// [`Vmctx::yield_val_expecting_val()`](vmctx/struct.Vmctx.html#method.yield_val_expecting_val).
///
/// The provided value will be dynamically typechecked against the type the guest expects to
/// receive, and if that check fails, this call will fail with `Error::InvalidArgument`.
///
/// # Safety
///
/// The foreign code safety caveat of [`Instance::run()`](struct.Instance.html#method.run)
/// applies.
pub fn resume_with_val<A: Any + 'static>(&mut self, val: A) -> Result<RunResult, Error> {
Ok(self.resume_with_val_impl(val, false, None)?.unwrap())
}
pub(crate) fn resume_with_val_impl<A: Any + 'static>(
&mut self,
val: A,
async_context: bool,
max_insn_count: Option<u64>,
) -> Result<InternalRunResult, Error> {
match &self.state {
State::Yielded { expecting, .. } => {
// make sure the resumed value is of the right type
if !expecting.is::<PhantomData<A>>() {
return Err(Error::InvalidArgument(
"type mismatch between yielded instance expected value and resumed value",
));
}
}
_ => return Err(Error::InvalidArgument("can only resume a yielded instance")),
}
self.resumed_val = Some(Box::new(val) as Box<dyn Any + 'static>);
self.set_instruction_bound_delta(max_insn_count);
self.swap_and_return(async_context)
}
/// Resume execution of an instance that has previously reached an instruction bound.
///
/// The execution slice that begins with this call is bounded by the new bound provided.
///
/// This should only be used when `run_func()` returned a `RunResult::Bounded`. This is an
/// internal function used by `run_async()`.
///
/// # Safety
///
/// The foreign code safety caveat of [`Instance::run()`](struct.Instance.html#method.run)
/// applies.
pub(crate) fn resume_bounded(
&mut self,
max_insn_count: u64,
) -> Result<InternalRunResult, Error> {
if !self.state.is_bound_expired() {
return Err(Error::InvalidArgument(
"can only call resume_bounded() on an instance that hit an instruction bound",
));
}
self.set_instruction_bound_delta(Some(max_insn_count));
self.swap_and_return(true)
}
/// Run the module's [start function][start], if one exists.
///
/// If there is no start function in the module, this does nothing.
///
/// If the module contains a start function, you must run it before running any other exported
/// functions. If an instance is reset, you must run the start function again.
///
/// Start functions may assume that Wasm tables and memories are properly initialized, but may
/// not assume that imported functions or globals are available.
///
/// # Errors
///
/// In addition to the errors that can be returned from [`Instance::run()`][run], this can also
/// return `Error::StartYielded` if the start function attempts to yield. This should not arise
/// as long as the start function does not attempt to use any imported functions.
///
/// This also returns `Error::StartAlreadyRun` if the start function has already run since the
/// instance was created or last reset.
///
/// Wasm start functions are not allowed to call imported functions. If the start function
/// attempts to do so, the instance will be terminated with
/// `TerminationDetails::StartCalledImportFunc`.
///
/// # Safety
///
/// The foreign code safety caveat of [`Instance::run()`][run]
/// applies.
///
/// [run]: struct.Instance.html#method.run
/// [start]: https://webassembly.github.io/spec/core/syntax/modules.html#syntax-start
pub fn run_start(&mut self) -> Result<(), Error> {
if let Some(start) = self.module.get_start_func()? {
if !self.is_not_started() {
return Err(Error::StartAlreadyRun);
}
self.run_func(start, &[], false, None)?;
}
Ok(())
}
/// Reset the instance's heap and global variables to their initial state.
///
/// The WebAssembly `start` section, if present, will need to be re-run with
/// [`Instance::run_start()`][run_start] before running any other exported functions.
///
/// The embedder contexts present at instance creation or added with
/// [`Instance::insert_embed_ctx()`](struct.Instance.html#method.insert_embed_ctx) are not
/// modified by this call; it is the embedder's responsibility to clear or reset their state if
/// necessary.
///
/// This will also reinitialize the kill state, which means that any outstanding
/// [`KillSwitch`](struct.KillSwitch.html) objects will be unable to terminate this instance.
/// It is the embedder's responsibility to initialize new `KillSwitch`es after resetting an
/// instance.
///
/// [run_start]: struct.Instance.html#method.run
pub fn reset(&mut self) -> Result<(), Error> {
self.alloc.reset_heap(self.module.as_ref())?;
let globals = unsafe { self.alloc.globals_mut() };
let mod_globals = self.module.globals();
for (i, v) in mod_globals.iter().enumerate() {
globals[i] = match v.global() {
Global::Import { .. } => {
return Err(Error::Unsupported(format!(
"global imports are unsupported; found: {:?}",
v
)));
}
Global::Def(def) => def.init_val(),
};
}
if self.module.get_start_func()?.is_some() {
self.state = State::NotStarted;
} else {
self.state = State::Ready;
}
#[cfg(feature = "concurrent_testpoints")]
{
self.kill_state = Arc::new(KillState::new(Arc::clone(&self.lock_testpoints)));
}
#[cfg(not(feature = "concurrent_testpoints"))]
{
self.kill_state = Arc::new(KillState::new());
}
Ok(())
}
/// Grow the guest memory by the given number of WebAssembly pages.
///
/// On success, returns the number of pages that existed before the call.
pub fn grow_memory(&mut self, additional_pages: u32) -> Result<u32, Error> {
let additional_bytes = additional_pages
.checked_mul(WASM_PAGE_SIZE)
.ok_or_else(|| lucet_format_err!("additional pages larger than wasm address space",))?;
let orig_len = self
.alloc
.expand_heap(additional_bytes, self.module.as_ref())?;
Ok(orig_len / WASM_PAGE_SIZE)
}
/// Return the WebAssembly heap as a slice of bytes.
pub fn heap(&self) -> &[u8] {
unsafe { self.alloc.heap() }
}
/// Return the WebAssembly heap as a mutable slice of bytes.
pub fn heap_mut(&mut self) -> &mut [u8] {
unsafe { self.alloc.heap_mut() }
}
/// Return the WebAssembly heap as a slice of `u32`s.
pub fn heap_u32(&self) -> &[u32] {
unsafe { self.alloc.heap_u32() }
}
/// Return the WebAssembly heap as a mutable slice of `u32`s.
pub fn heap_u32_mut(&mut self) -> &mut [u32] {
unsafe { self.alloc.heap_u32_mut() }
}
/// Return the WebAssembly globals as a slice of `i64`s.
pub fn globals(&self) -> &[GlobalValue] {
unsafe { self.alloc.globals() }
}
/// Return the WebAssembly globals as a mutable slice of `i64`s.
pub fn globals_mut(&mut self) -> &mut [GlobalValue] {
unsafe { self.alloc.globals_mut() }
}
/// Check whether a given range in the host address space overlaps with the memory that backs
/// the instance heap.
pub fn check_heap<T>(&self, ptr: *const T, len: usize) -> bool {
self.alloc.mem_in_heap(ptr, len)
}
/// Check whether a context value of a particular type exists.
pub fn contains_embed_ctx<T: Any>(&self) -> bool {
self.embed_ctx.contains::<T>()
}
/// Get a reference to a context value of a particular type, if it exists.
pub fn get_embed_ctx<T: Any>(&self) -> Option<Result<Ref<'_, T>, BorrowError>> {
self.embed_ctx.try_get::<T>()
}
/// Get a mutable reference to a context value of a particular type, if it exists.
pub fn get_embed_ctx_mut<T: Any>(&self) -> Option<Result<RefMut<'_, T>, BorrowMutError>> {
self.embed_ctx.try_get_mut::<T>()
}
/// Insert a context value.
///
/// If a context value of the same type already existed, it is returned.
pub fn insert_embed_ctx<T: Any>(&mut self, x: T) -> Option<T> {
self.embed_ctx.insert(x)
}
/// Remove a context value of a particular type, returning it if it exists.
pub fn remove_embed_ctx<T: Any>(&mut self) -> Option<T> {
self.embed_ctx.remove::<T>()
}
/// Set the handler run when `SIGBUS`, `SIGFPE`, `SIGILL`, or `SIGSEGV` are caught by the
/// instance thread.
///
/// In most cases, these signals are unrecoverable for the instance that raised them, but do not
/// affect the rest of the process.
///
/// The default signal handler returns
/// [`SignalBehavior::Default`](enum.SignalBehavior.html#variant.Default), which yields a
/// runtime fault error.
///
/// The signal handler must be
/// [signal-safe](http://man7.org/linux/man-pages/man7/signal-safety.7.html).
pub fn set_signal_handler<H>(&mut self, handler: H)
where
H: 'static
+ Fn(
&Instance,
&Option<TrapCode>,
libc::c_int,
*const siginfo_t,
*const c_void,
) -> SignalBehavior,
{
self.signal_handler = Box::new(handler) as Box<SignalHandler>;
}
/// Set the handler run for signals that do not arise from a known WebAssembly trap, or that
/// involve memory outside of the current instance.
///
/// Fatal signals are not only unrecoverable for the instance that raised them, but may
/// compromise the correctness of the rest of the process if unhandled.
///
/// The default fatal handler calls `panic!()`.
pub fn set_fatal_handler(&mut self, handler: fn(&Instance) -> !) {
self.fatal_handler = handler;
}
/// Set the fatal handler to a C-compatible function.
///
/// This is a separate interface, because C functions can't return the `!` type. Like the
/// regular `fatal_handler`, it is not expected to return, but we cannot enforce that through
/// types.
///
/// When a fatal error occurs, this handler is run first, and then the regular `fatal_handler`
/// runs in case it returns.
pub fn set_c_fatal_handler(&mut self, handler: unsafe extern "C" fn(*mut Instance)) {
self.c_fatal_handler = Some(handler);
}
/// Set whether the Lucet signal handler is installed when running or resuming this instance
/// (`true` by default).
///
/// If this is `true`, the Lucet runtime checks whether its signal handler is installed whenever
/// an instance runs, installing it if it is not present, and uninstalling it when there are no
/// longer any Lucet instances running. If this is `false`, that check is disabled, which can
/// improve performance when running or resuming an instance.
///
/// Use `install_lucet_signal_handler()` and `remove_lucet_signal_handler()` to manually install
/// or remove the signal handler.
///
/// # Safety
///
/// If the Lucet signal handler is not installed when an instance runs, WebAssembly traps such
/// as division by zero, assertion failures, or out-of-bounds memory access will raise signals
/// to the default signal handlers, usually causing the entire process to crash.
pub fn ensure_signal_handler_installed(&mut self, ensure: bool) {
self.ensure_signal_handler_installed = ensure;
}
/// Set whether an alternate signal stack is installed for the current thread when running or
/// resuming this instance (`true` by default).
///
/// If this is `true`, the Lucet runtime installs an alternate signal stack whenever an instance
/// runs, and uninstalls it afterwards. If this is `false`, the signal stack is not
/// automatically manipulated.
///
/// The automatically-installed signal stack uses space allocated in the instance's `Region`,
/// sized according to the `signal_stack_size` field of the region's `Limits`.
///
/// If you wish to instead provide your own signal stack, we recommend using a stack of size
/// `DEFAULT_SIGNAL_STACK_SIZE`, which varies depending on platform and optimization level.
///
/// Signal stacks are installed on a per-thread basis, so any thread that runs this instance
/// must have a signal stack installed.
///
/// # Safety
///
/// If an alternate signal stack is not installed when an instance runs, there may not be enough
/// stack space for the Lucet signal handler to run. If the signal handler runs out of stack
/// space, a double fault could occur and crash the entire process, or the program could
/// continue with corrupted memory.
pub fn ensure_sigstack_installed(&mut self, ensure: bool) {
self.ensure_sigstack_installed = ensure;
}
pub fn kill_switch(&self) -> KillSwitch {
KillSwitch::new(Arc::downgrade(&self.kill_state))
}
pub fn is_not_started(&self) -> bool {
self.state.is_not_started()
}
pub fn is_ready(&self) -> bool {
self.state.is_ready()
}
pub fn is_yielded(&self) -> bool {
self.state.is_yielded()
}
pub fn is_bound_expired(&self) -> bool {
self.state.is_bound_expired()
}
pub fn is_faulted(&self) -> bool {
self.state.is_faulted()
}
pub fn is_terminated(&self) -> bool {
self.state.is_terminated()
}
// This needs to be public as it's used in the expansion of `lucet_hostcalls`, available for
// external use. But you *really* shouldn't have to call this yourself, so we're going to keep
// it out of rustdoc.
#[doc(hidden)]
pub fn uninterruptable<T, F: FnOnce() -> T>(&mut self, f: F) -> T {
self.kill_state.begin_hostcall();
let res = f();
let stop_reason = self.kill_state.end_hostcall();
if let Some(termination_details) = stop_reason {
// TODO: once we have unwinding, panic here instead so we unwind host frames
unsafe {
self.terminate(termination_details);
}
}
res
}
#[inline]
pub fn get_instruction_count(&self) -> Option<u64> {
if self.module.is_instruction_count_instrumented() {
let implicits = self.get_instance_implicits();
let sum = implicits.instruction_count_bound + implicits.instruction_count_adj;
// This invariant is ensured as we always set up the fields to have a positive sum, and
// generated code only increments `adj`.
debug_assert!(sum >= 0);
return Some(sum as u64);
}
None
}
/// Set the total instruction count and bound.
#[inline]
pub fn set_instruction_count_and_bound(&mut self, instruction_count: u64, bound: u64) {
let implicits = self.get_instance_implicits_mut();
let instruction_count =
i64::try_from(instruction_count).expect("instruction count too large");
let bound = i64::try_from(bound).expect("bound too large");
// These two sum to `instruction_count`, which must be non-negative.
implicits.instruction_count_bound = bound;
implicits.instruction_count_adj = instruction_count - bound;
}
/// Set the instruction bound to be `delta` above the current count.
///
/// See the comments on `instruction_count_adj` in `InstanceRuntimeData` for more details on
/// how this bound works; most relevant is that a bound-yield is only triggered if the bound
/// value is *crossed*, but not if execution *begins* with the value exceeded. Hence `delta`
/// must be greater than zero for this to set up the instance state to trigger a yield.
#[inline]
pub fn set_instruction_bound_delta(&mut self, delta: Option<u64>) {
let implicits = self.get_instance_implicits_mut();
let sum = implicits.instruction_count_adj + implicits.instruction_count_bound;
let delta = delta.unwrap_or(i64::MAX as u64);
let delta = i64::try_from(delta).expect("delta too large");
implicits.instruction_count_bound = sum.wrapping_add(delta);
implicits.instruction_count_adj = -delta;
}
#[inline]
pub fn set_hostcall_stack_reservation(&mut self) {
let slot = self
.alloc
.slot
.as_ref()
.expect("reachable instance has a slot");
let reservation = slot.limits.hostcall_reservation;
// The `.stack` field is a pointer to the lowest address of the stack - the start of its
// allocation. Because the stack grows downward, this is the end of the stack space. So the
// limit we'll need to check for hostcalls is some reserved space upwards from here, to
// meet some guest stack pointer early.
self.get_instance_implicits_mut().stack_limit = slot.stack as u64 + reservation as u64;
}
#[inline]
pub fn terminate_on_heap_oom(&self) -> bool {
self.terminate_on_heap_oom
}
#[inline]
pub fn set_terminate_on_heap_oom(&mut self, terminate_on_heap_oom: bool) {
self.terminate_on_heap_oom = terminate_on_heap_oom;
}
}
// Private API
impl Instance {
fn new(alloc: Alloc, module: Arc<dyn Module>, embed_ctx: CtxMap) -> Self {
let globals_ptr = alloc.slot().globals as *mut i64;
#[cfg(feature = "concurrent_testpoints")]
let lock_testpoints = Arc::new(LockTestpoints::new());