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
use crate::instance::siginfo_ext::SiginfoExt;
use crate::instance::{FaultDetails, TerminationDetails, YieldedVal};
use crate::sysdeps::UContext;
use libc::{SIGBUS, SIGSEGV};
use std::any::Any;
use std::ffi::{CStr, CString};

/// The representation of a Lucet instance's state machine.
pub enum State {
    /// The instance is ready to run.
    ///
    /// Transitions to `Running` when the instance is run, or to `Ready` when it's reset.
    Ready,

    /// The instance is running.
    ///
    /// Transitions to `Ready` when the guest function returns normally, or to `Faulted`,
    /// `Terminating`, or `Yielding` if the instance faults, terminates, or yields.
    Running,

    /// The instance has faulted, potentially fatally.
    ///
    /// Transitions to `Faulted` when filling in additional fault details, to `Running` if
    /// re-running a non-fatally faulted instance, or to `Ready` when the instance is reset.
    Faulted {
        details: FaultDetails,
        siginfo: libc::siginfo_t,
        context: UContext,
    },

    /// The instance is in the process of terminating.
    ///
    /// Transitions only to `Terminated`; the `TerminationDetails` are always extracted into a
    /// `RunResult` before anything else happens to the instance.
    Terminating { details: TerminationDetails },

    /// The instance has terminated, and must be reset before running again.
    ///
    /// Transitions to `Ready` if the instance is reset.
    Terminated,

    /// The instance is in the process of yielding.
    ///
    /// Transitions only to `Yielded`; the `YieldedVal` is always extracted into a
    /// `RunResult` before anything else happens to the instance.
    Yielding {
        val: YieldedVal,
        /// A phantom value carrying the type of the expected resumption value.
        ///
        /// Concretely, this should only ever be `Box<PhantomData<R>>` where `R` is the type
        /// the guest expects upon resumption.
        expecting: Box<dyn Any>,
    },

    /// The instance has yielded.
    ///
    /// Transitions to `Running` if the instance is resumed, or to `Ready` if the instance is reset.
    Yielded {
        /// A phantom value carrying the type of the expected resumption value.
        ///
        /// Concretely, this should only ever be `Box<PhantomData<R>>` where `R` is the type
        /// the guest expects upon resumption.
        expecting: Box<dyn Any>,
    },

    /// A placeholder state used with `std::mem::replace()` when a new state must be constructed by
    /// moving values out of an old state.
    ///
    /// This is used so that we do not need a `Clone` impl for this type, which would add
    /// unnecessary constraints to the types of values instances could yield or terminate with.
    ///
    /// It is an error for this state to appear outside of a transition between other states.
    Transitioning,
}

impl std::fmt::Display for State {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            State::Ready => write!(f, "ready"),
            State::Running => write!(f, "running"),
            State::Faulted {
                details, siginfo, ..
            } => {
                write!(f, "{}", details)?;
                write!(
                    f,
                    " triggered by {}: ",
                    strsignal_wrapper(siginfo.si_signo)
                        .into_string()
                        .expect("strsignal returns valid UTF-8")
                )?;

                if siginfo.si_signo == SIGSEGV || siginfo.si_signo == SIGBUS {
                    // We know this is inside the heap guard, because by the time we get here,
                    // `lucet_error_verify_trap_safety` will have run and validated it.
                    write!(
                        f,
                        " accessed memory at {:p} (inside heap guard)",
                        siginfo.si_addr_ext()
                    )?;
                }
                Ok(())
            }
            State::Terminated { .. } => write!(f, "terminated"),
            State::Terminating { .. } => write!(f, "terminating"),
            State::Yielding { .. } => write!(f, "yielding"),
            State::Yielded { .. } => write!(f, "yielded"),
            State::Transitioning { .. } => {
                write!(f, "transitioning (IF YOU SEE THIS, THERE'S PROBABLY A BUG)")
            }
        }
    }
}

impl State {
    pub fn is_ready(&self) -> bool {
        if let State::Ready { .. } = self {
            true
        } else {
            false
        }
    }

    pub fn is_running(&self) -> bool {
        if let State::Running = self {
            true
        } else {
            false
        }
    }

    pub fn is_fault(&self) -> bool {
        if let State::Faulted { .. } = self {
            true
        } else {
            false
        }
    }

    pub fn is_fatal(&self) -> bool {
        if let State::Faulted {
            details: FaultDetails { fatal, .. },
            ..
        } = self
        {
            *fatal
        } else {
            false
        }
    }

    pub fn is_terminated(&self) -> bool {
        if let State::Terminated { .. } = self {
            true
        } else {
            false
        }
    }

    pub fn is_yielded(&self) -> bool {
        if let State::Yielded { .. } = self {
            true
        } else {
            false
        }
    }
}

// TODO: PR into `libc`
extern "C" {
    #[no_mangle]
    fn strsignal(sig: libc::c_int) -> *mut libc::c_char;
}

// TODO: PR into `nix`
fn strsignal_wrapper(sig: libc::c_int) -> CString {
    unsafe { CStr::from_ptr(strsignal(sig)).to_owned() }
}