use std::fmt;
use std::num::NonZeroUsize;
use std::str::FromStr;
use nix::sys::signal::Signal;
use reverie_syscalls::Sysno;
use serde::Deserialize;
use serde::Serialize;
use serde::Serializer;
use serde::de;
use crate::pid::DetTid;
use crate::time::DetTime;
use crate::time::LogicalDuration;
use crate::time::LogicalTime;
pub mod boundary;
#[derive(PartialEq, Debug, Eq, Clone, Copy, Serialize, Deserialize, Hash)]
pub struct InstructionOffset {
pub rcb_target: u64,
pub instructions: u64,
}
#[derive(PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct SchedEvent {
pub dettid: DetTid,
pub op: Op,
pub count: u32,
pub start_rip: Option<InstructionPointer>,
pub end_rip: Option<InstructionPointer>,
pub end_time: Option<LogicalTime>,
#[serde(default)]
pub stopless: bool,
#[serde(default)]
pub instruction_offset: Option<InstructionOffset>,
}
impl Serialize for SchedEvent {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let Self {
dettid,
op,
count,
start_rip,
end_rip,
end_time,
stopless,
instruction_offset,
} = self;
let binary = !serializer.is_human_readable();
let written_stopless = *stopless || binary;
let written_offset = instruction_offset.is_some() || binary;
let mut state = serializer.serialize_struct(
"SchedEvent",
6 + usize::from(written_stopless) + usize::from(written_offset),
)?;
state.serialize_field("dettid", dettid)?;
state.serialize_field("op", op)?;
state.serialize_field("count", count)?;
state.serialize_field("start_rip", start_rip)?;
state.serialize_field("end_rip", end_rip)?;
state.serialize_field("end_time", end_time)?;
if written_stopless {
state.serialize_field("stopless", stopless)?;
} else {
state.skip_field("stopless")?;
}
if written_offset {
state.serialize_field("instruction_offset", instruction_offset)?;
} else {
state.skip_field("instruction_offset")?;
}
state.end()
}
}
impl fmt::Debug for SchedEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
dettid,
op,
count,
start_rip,
end_rip,
end_time,
stopless,
instruction_offset,
} = self;
let mut s = f.debug_struct("SchedEvent");
s.field("dettid", dettid)
.field("op", op)
.field("count", count)
.field("start_rip", start_rip)
.field("end_rip", end_rip)
.field("end_time", end_time);
if *stopless {
s.field("stopless", stopless);
}
if let Some(offset) = instruction_offset {
s.field("instruction_offset", offset);
}
s.finish()
}
}
impl fmt::Display for SchedEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(tid{}", self.dettid)?;
if self.count > 1 {
write!(f, " cnt={}", self.count)?;
}
if let Some(srip) = self.start_rip {
write!(f, " strt={:#x}", srip)?;
}
if let Some(erip) = self.end_rip {
write!(f, " end={:#x}", erip)?;
}
if let Some(time) = self.end_time {
write!(f, " time={}", time)?;
}
if self.stopless {
write!(f, " stopless")?;
}
if let Some(offset) = self.instruction_offset {
write!(
f,
" offset=+{}@rcb{}",
offset.instructions, offset.rcb_target
)?;
}
write!(f, " {:?})", self.op)?;
Ok(())
}
}
impl SchedEvent {
pub fn syscall(dettid: DetTid, sysno: Sysno, phase: SyscallPhase) -> SchedEvent {
SchedEvent {
dettid,
op: Op::Syscall(sysno, phase),
count: 1,
start_rip: None,
end_rip: None,
end_time: None,
stopless: false,
instruction_offset: None,
}
}
pub fn branches(dettid: DetTid, count: u32) -> SchedEvent {
SchedEvent {
dettid,
op: Op::Branch,
count,
start_rip: None, end_rip: None,
end_time: None,
stopless: false,
instruction_offset: None,
}
}
pub fn with_time(mut self, time: LogicalDuration) -> SchedEvent {
self.end_time = Some(time);
self
}
pub fn with_dettime(mut self, dt: &DetTime) -> SchedEvent {
self.end_time = Some(dt.without_starting());
self
}
pub fn with_start_rip(mut self, start_rip: InstructionPointer) -> Self {
self.start_rip = Some(start_rip);
self
}
pub fn with_end_rip(mut self, end_rip: InstructionPointer) -> Self {
assert!(
!self.stopless,
"a slice end without a stop has no RIP: {self:?}"
);
self.end_rip = Some(end_rip);
self
}
pub fn stopless_mark_refusal(&self) -> Option<&'static str> {
if !self.stopless {
None
} else if self.op != Op::Branch {
Some("only the branches up to a timeslice end may be marked `stopless`")
} else if self.end_rip.is_some() {
Some(
"a timeslice end marked `stopless` has no end RIP: the guest was not stopped there",
)
} else if self.instruction_offset.is_some() {
Some(
"a timeslice end marked `stopless` has no instruction offset: an offset is stepped \
from a stop at its branch target",
)
} else {
None
}
}
pub fn same_kind(&self, other: &SchedEvent) -> bool {
let rips_known = !(self.stopless || other.stopless);
(self.dettid, self.op, self.start_rip) == (other.dettid, other.op, other.start_rip)
&& (!rips_known || self.end_rip == other.end_rip)
&& self.instruction_offset == other.instruction_offset
}
pub fn same_operations(&self, other: &SchedEvent) -> bool {
self.same_kind(other) && (self.count, self.end_time) == (other.count, other.end_time)
}
pub fn taken_without_stop(mut self) -> Self {
assert_eq!(self.op, Op::Branch, "only branches end at a timeslice end");
assert!(
self.end_rip.is_none(),
"a slice end without a stop has no RIP"
);
assert!(
self.instruction_offset.is_none(),
"a slice end without a stop has no instruction offset"
);
self.stopless = true;
self
}
pub fn with_instruction_offset(mut self, offset: Option<InstructionOffset>) -> Self {
assert!(
!(self.stopless && offset.is_some()),
"a slice end without a stop has no instruction offset: {self:?}"
);
self.instruction_offset = offset;
self
}
}
pub type InstructionPointer = NonZeroUsize;
#[derive(PartialEq, Debug, Eq, Copy, Clone, Hash, Serialize, Deserialize)]
pub enum SyscallPhase {
Prehook,
Polling,
Posthook,
}
#[derive(PartialEq, Debug, Eq, Clone, Copy, Hash, PartialOrd, Ord)]
pub struct SigWrapper(pub i32);
impl SigWrapper {
pub fn raw(&self) -> i32 {
self.0
}
pub fn signal(&self) -> Option<Signal> {
Signal::try_from(self.0).ok()
}
pub fn as_string(&self) -> String {
match self.signal() {
Some(signal) => signal.as_str().to_string(),
None => format!("SIG{}", self.0),
}
}
}
impl std::fmt::Display for SigWrapper {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_string())
}
}
impl Serialize for SigWrapper {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.as_string())
}
}
impl<'de> de::Deserialize<'de> for SigWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
struct SignalVisitor;
impl<'de> de::Visitor<'de> for SignalVisitor {
type Value = SigWrapper;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "string representing a signal")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
SigWrapper::from_str(v).map_err(serde::de::Error::custom)
}
}
deserializer.deserialize_str(SignalVisitor)
}
}
impl FromStr for SigWrapper {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
if let Ok(signal) = Signal::from_str(s) {
return Ok(SigWrapper(signal as i32));
}
if let Some(rest) = s.strip_prefix("SIG")
&& let Ok(raw) = rest.parse::<i32>()
&& raw > 0
{
return Ok(SigWrapper(raw));
}
anyhow::bail!("not a signal: {s}")
}
}
impl From<Signal> for SigWrapper {
fn from(signal: Signal) -> Self {
Self(signal as i32)
}
}
#[cfg(test)]
mod sched_event_tests {
use super::*;
fn event(stopless: bool) -> SchedEvent {
SchedEvent {
end_time: Some(LogicalTime::from_nanos(1_250)),
stopless,
..SchedEvent::branches(DetTid::from_raw(3), 100)
}
}
#[test]
fn json_leaves_out_a_false_stopless_and_reads_its_absence_as_false() {
let before = r#"{"dettid":3,"op":"Branch","count":100,"start_rip":null,"end_rip":null,"end_time":1250}"#;
assert_eq!(serde_json::to_string(&event(false)).unwrap(), before);
assert_eq!(
serde_json::from_str::<SchedEvent>(before).unwrap(),
event(false)
);
let stopless = serde_json::to_string(&event(true)).unwrap();
assert_eq!(
stopless,
r#"{"dettid":3,"op":"Branch","count":100,"start_rip":null,"end_rip":null,"end_time":1250,"stopless":true}"#
);
assert_eq!(
serde_json::from_str::<SchedEvent>(&stopless).unwrap(),
event(true)
);
}
#[test]
fn a_binary_encoding_keeps_stopless_in_place() {
for stopless in [false, true] {
let pair = (event(stopless), 7u32);
let wire = bincode::serde::encode_to_vec(&pair, bincode::config::legacy()).unwrap();
let (back, _): ((SchedEvent, u32), usize) =
bincode::serde::decode_from_slice(&wire, bincode::config::legacy()).unwrap();
assert_eq!(back, pair);
}
}
#[test]
fn same_operations_ignores_only_how_a_slice_end_was_taken() {
let stopped = SchedEvent {
end_rip: InstructionPointer::new(0x1000),
..event(false)
};
assert!(stopped.same_operations(&event(true)));
assert!(event(true).same_operations(&stopped));
assert!(stopped.same_operations(&stopped.clone()));
let elsewhere = SchedEvent {
end_rip: InstructionPointer::new(0x2000),
..stopped.clone()
};
assert!(!stopped.same_operations(&elsewhere));
let later = SchedEvent {
count: 101,
..event(true)
};
assert!(!stopped.same_operations(&later));
let offset = |instructions| {
Some(InstructionOffset {
rcb_target: 98,
instructions,
})
};
let at_offset = stopped.clone().with_instruction_offset(offset(3));
assert!(at_offset.same_operations(&at_offset.clone()));
assert!(!at_offset.same_operations(&stopped));
assert!(!stopped.same_kind(&at_offset));
assert!(!at_offset.same_kind(&stopped.clone().with_instruction_offset(offset(4))));
}
#[test]
fn debug_shows_stopless_only_when_set() {
let plain = format!("{:?}", event(false));
assert_eq!(
plain,
"SchedEvent { dettid: DetPid(3), op: Branch, count: 100, start_rip: None, end_rip: None, end_time: Some(LogicalTime(1250)) }"
);
assert_eq!(
format!("{:?}", event(true)),
plain.replace(" }", ", stopless: true }")
);
}
#[test]
#[should_panic(expected = "a slice end without a stop has no RIP")]
fn a_slice_end_without_a_stop_has_no_rip() {
let _ = SchedEvent::branches(DetTid::from_raw(3), 1)
.with_end_rip(InstructionPointer::new(0x1000).unwrap())
.taken_without_stop();
}
#[test]
#[should_panic(expected = "a slice end without a stop has no RIP")]
fn a_rip_cannot_be_set_on_a_slice_end_taken_without_a_stop() {
let _ = SchedEvent::branches(DetTid::from_raw(3), 1)
.taken_without_stop()
.with_end_rip(InstructionPointer::new(0x1000).unwrap());
}
}
#[cfg(test)]
mod sigwrapper_tests {
use super::*;
#[test]
fn every_previously_representable_signal_serializes_byte_identically() {
for raw in 1..=31i32 {
let Ok(signal) = Signal::try_from(raw) else {
continue;
};
let wrapper = SigWrapper::from(signal);
let json = serde_json::to_string(&wrapper).expect("serialize");
let expected = serde_json::to_string(signal.as_str()).expect("serialize name");
assert_eq!(
json,
expected,
"signal {raw} ({}) changed its serialized form",
signal.as_str()
);
}
}
#[test]
fn realtime_signals_gain_a_distinct_spelling() {
for raw in 32..=64i32 {
let wrapper = SigWrapper(raw);
assert_eq!(wrapper.as_string(), format!("SIG{raw}"));
assert_eq!(wrapper.signal(), None, "nix must still not name {raw}");
}
}
#[test]
fn every_signal_round_trips_through_serde_and_fromstr() {
for raw in 1..=64i32 {
let wrapper = SigWrapper(raw);
let json = serde_json::to_string(&wrapper).expect("serialize");
let back: SigWrapper = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back, wrapper, "serde round-trip lost signal {raw}");
let parsed = SigWrapper::from_str(&wrapper.as_string()).expect("from_str");
assert_eq!(parsed, wrapper, "FromStr round-trip lost signal {raw}");
}
}
#[test]
fn both_spellings_deserialize() {
let by_name: SigWrapper = serde_json::from_str("\"SIGUSR1\"").expect("name");
assert_eq!(by_name, SigWrapper::from(Signal::SIGUSR1));
let by_number: SigWrapper = serde_json::from_str("\"SIG40\"").expect("number");
assert_eq!(by_number, SigWrapper(40));
}
}
#[cfg(test)]
mod instruction_offset_tests {
use super::*;
mod before {
use super::*;
#[derive(Debug, Serialize)]
pub struct SchedEvent {
pub dettid: DetTid,
pub op: Op,
pub count: u32,
pub start_rip: Option<InstructionPointer>,
pub end_rip: Option<InstructionPointer>,
pub end_time: Option<LogicalTime>,
}
}
fn branch(offset: Option<InstructionOffset>) -> SchedEvent {
SchedEvent::branches(DetTid::from_raw(3), 7)
.with_end_rip(NonZeroUsize::new(4096).unwrap())
.with_time(LogicalTime::from_nanos(70))
.with_instruction_offset(offset)
}
#[test]
fn an_absent_offset_leaves_an_event_unchanged_and_a_present_one_round_trips() {
let plain = branch(None);
let old = before::SchedEvent {
dettid: plain.dettid,
op: plain.op,
count: plain.count,
start_rip: plain.start_rip,
end_rip: plain.end_rip,
end_time: plain.end_time,
};
let json = serde_json::to_string(&plain).unwrap();
assert_eq!(json, serde_json::to_string(&old).unwrap());
assert_eq!(
serde_json::to_string_pretty(&plain).unwrap(),
serde_json::to_string_pretty(&old).unwrap()
);
assert_eq!(serde_json::from_str::<SchedEvent>(&json).unwrap(), plain);
assert_eq!(format!("{plain:?}"), format!("{old:?}"));
assert_eq!(format!("{plain:#?}"), format!("{old:#?}"));
assert!(!format!("{plain}").contains("offset"));
let offset = InstructionOffset {
rcb_target: 40,
instructions: 5,
};
let with = branch(Some(offset));
let json = serde_json::to_string(&with).unwrap();
assert!(
json.ends_with(r#","instruction_offset":{"rcb_target":40,"instructions":5}}"#),
"{json}"
);
assert_eq!(serde_json::from_str::<SchedEvent>(&json).unwrap(), with);
assert_ne!(with, plain);
assert!(format!("{with:?}").ends_with(
"instruction_offset: InstructionOffset { rcb_target: 40, instructions: 5 } }"
));
assert!(format!("{with}").contains(" offset=+5@rcb40 "), "{with}");
for event in [plain, with] {
let config = bincode::config::standard();
let encoded = bincode::serde::encode_to_vec(&event, config).unwrap();
let (decoded, _): (SchedEvent, usize) =
bincode::serde::decode_from_slice(&encoded, config).unwrap();
assert_eq!(decoded, event);
}
}
}
#[derive(PartialEq, Debug, Eq, Copy, Clone, Hash, Serialize, Deserialize)]
pub enum Op {
Branch,
Rdtsc,
Cpuid,
Syscall(Sysno, SyscallPhase),
OtherInstructions,
SignalReceived(SigWrapper),
}