1use std::fs::File;
35use std::io::{BufReader, BufWriter, Read, Write};
36use std::path::{Path, PathBuf};
37
38use flate2::Compression;
39use flate2::read::MultiGzDecoder;
40use flate2::write::GzEncoder;
41
42use crate::error::{Error, Result};
43use crate::record::{AccessClass, AccessKind, AccessOutcome, InstructionOutcome, InstructionRecord};
44
45pub const MAGIC: &[u8; 8] = b"KVTSIDE\0";
47pub const VERSION: u32 = 1;
49pub const ENTRY_SIZE: usize = 72;
51pub const ACCESS_SIZE: usize = 32;
53pub const NO_PHYS: u64 = u64::MAX;
55
56pub const ACCESS_CONDITIONAL: u8 = 1;
58pub const ACCESS_IN_MACSIM: u8 = 2;
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct SideAccess {
65 pub linear: u64,
67 pub physical: u64,
69 pub physical_end: u64,
72 pub size: u32,
74 pub kind: u8,
76 pub class: u8,
78 pub outcome: u8,
80 pub flags: u8,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct SideEntry {
87 pub raw_index: u64,
89 pub global_seq: u64,
91 pub local_seq: u64,
93 pub cr3: u64,
95 pub physical_pc: u64,
97 pub cs: u16,
101 pub flags: u16,
103 pub cpl: u8,
105 pub mode: u8,
107 pub outcome: u8,
109 pub vector: u8,
111 pub len: u8,
113 pub bytes: [u8; 15],
115 pub vcpu: u32,
117 pub accesses: Vec<SideAccess>,
119}
120
121fn kind_code(k: AccessKind) -> u8 {
122 match k {
123 AccessKind::Read => 0,
124 AccessKind::Write => 1,
125 AccessKind::ReadWrite => 2,
126 AccessKind::Fetch => 3,
127 }
128}
129
130fn class_code(c: AccessClass) -> u8 {
131 match c {
132 AccessClass::Operand => 0,
133 AccessClass::Implicit => 1,
134 AccessClass::Prefetch => 2,
135 AccessClass::InstructionFetch => 3,
136 AccessClass::EventDescriptor => 4,
137 AccessClass::EventFrame => 5,
138 }
139}
140
141fn outcome_code(o: AccessOutcome) -> u8 {
142 match o {
143 AccessOutcome::Performed => 0,
144 AccessOutcome::Faulted => 1,
145 AccessOutcome::Aborted => 2,
146 AccessOutcome::Suppressed => 3,
147 }
148}
149
150impl SideEntry {
151 pub fn from_record(rec: &InstructionRecord, raw_index: u64, in_macsim: &[usize]) -> SideEntry {
155 let (outcome, vector) = match rec.outcome {
156 InstructionOutcome::Retired => (0, 0),
157 InstructionOutcome::RepIteration => (1, 0),
158 InstructionOutcome::Faulted { vector } => (2, vector),
159 };
160 SideEntry {
161 raw_index,
162 global_seq: rec.seq.global,
163 local_seq: rec.seq.local,
164 cr3: rec.cr3,
165 physical_pc: rec.physical_rip.unwrap_or(NO_PHYS),
166 cs: rec.cs,
167 flags: rec.flags.bits(),
168 cpl: rec.cpl,
169 mode: rec.mode.as_u8(),
170 outcome,
171 vector,
172 len: rec.len,
173 bytes: rec.bytes,
174 vcpu: rec.vcpu,
175 accesses: rec
176 .accesses
177 .iter()
178 .enumerate()
179 .map(|(k, a)| SideAccess {
180 linear: a.linear,
181 physical: a.physical.unwrap_or(NO_PHYS),
182 physical_end: a.physical_end.unwrap_or(NO_PHYS),
183 size: a.size,
184 kind: kind_code(a.kind),
185 class: class_code(a.class),
186 outcome: outcome_code(a.outcome),
187 flags: (if a.conditional { ACCESS_CONDITIONAL } else { 0 })
188 | (if in_macsim.contains(&k) { ACCESS_IN_MACSIM } else { 0 }),
189 })
190 .collect(),
191 }
192 }
193
194 pub fn cs_rpl(&self) -> u8 {
196 (self.cs & 3) as u8
197 }
198
199 fn header_bytes(&self) -> [u8; ENTRY_SIZE] {
200 let mut b = [0u8; ENTRY_SIZE];
201 b[0..8].copy_from_slice(&self.raw_index.to_le_bytes());
202 b[8..16].copy_from_slice(&self.global_seq.to_le_bytes());
203 b[16..24].copy_from_slice(&self.local_seq.to_le_bytes());
204 b[24..32].copy_from_slice(&self.cr3.to_le_bytes());
205 b[32..40].copy_from_slice(&self.physical_pc.to_le_bytes());
206 b[40..42].copy_from_slice(&self.cs.to_le_bytes());
207 b[42..44].copy_from_slice(&self.flags.to_le_bytes());
208 b[44] = self.cpl;
209 b[45] = self.mode;
210 b[46] = self.outcome;
211 b[47] = self.vector;
212 b[48] = self.len;
213 b[49..64].copy_from_slice(&self.bytes);
214 b[64..68].copy_from_slice(&self.vcpu.to_le_bytes());
215 b[68..70].copy_from_slice(&(self.accesses.len().min(u16::MAX as usize) as u16).to_le_bytes());
216 b
217 }
218}
219
220impl SideAccess {
221 fn to_bytes(self) -> [u8; ACCESS_SIZE] {
222 let mut b = [0u8; ACCESS_SIZE];
223 b[0..8].copy_from_slice(&self.linear.to_le_bytes());
224 b[8..16].copy_from_slice(&self.physical.to_le_bytes());
225 b[16..24].copy_from_slice(&self.physical_end.to_le_bytes());
226 b[24..28].copy_from_slice(&self.size.to_le_bytes());
227 b[28] = self.kind;
228 b[29] = self.class;
229 b[30] = self.outcome;
230 b[31] = self.flags;
231 b
232 }
233
234 fn from_bytes(b: &[u8; ACCESS_SIZE]) -> SideAccess {
235 let u64_at = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap());
236 SideAccess {
237 linear: u64_at(0),
238 physical: u64_at(8),
239 physical_end: u64_at(16),
240 size: u32::from_le_bytes(b[24..28].try_into().unwrap()),
241 kind: b[28],
242 class: b[29],
243 outcome: b[30],
244 flags: b[31],
245 }
246 }
247}
248
249pub fn side_path(base: &Path, tid: u32) -> PathBuf {
251 let mut s = base.as_os_str().to_owned();
252 s.push(format!("_{tid}.side"));
253 PathBuf::from(s)
254}
255
256pub struct SideWriter {
258 out: GzEncoder<BufWriter<File>>,
259}
260
261impl SideWriter {
262 pub fn create(base: &Path, tid: u32, level: u32) -> Result<SideWriter> {
264 let f = File::create(side_path(base, tid))?;
265 let mut out = GzEncoder::new(BufWriter::with_capacity(1 << 20, f), Compression::new(level));
266 out.write_all(MAGIC)?;
267 for v in [VERSION, tid, ENTRY_SIZE as u32, ACCESS_SIZE as u32] {
268 out.write_all(&v.to_le_bytes())?;
269 }
270 Ok(SideWriter { out })
271 }
272
273 pub fn write(&mut self, e: &SideEntry) -> Result<()> {
275 self.out.write_all(&e.header_bytes())?;
276 for a in e.accesses.iter().take(u16::MAX as usize) {
277 self.out.write_all(&a.to_bytes())?;
278 }
279 Ok(())
280 }
281
282 pub fn finish(self) -> Result<()> {
284 self.out.finish()?.flush()?;
285 Ok(())
286 }
287}
288
289pub struct SideReader {
291 inp: MultiGzDecoder<BufReader<File>>,
292 vcpu: u32,
293}
294
295impl SideReader {
296 pub fn open(path: &Path) -> Result<SideReader> {
298 let mut inp = MultiGzDecoder::new(BufReader::new(File::open(path)?));
299 let mut h = [0u8; 24];
300 inp.read_exact(&mut h)?;
301 let word = |k: usize| u32::from_le_bytes(h[8 + 4 * k..12 + 4 * k].try_into().unwrap());
302 if &h[..8] != MAGIC || word(0) != VERSION || word(2) as usize != ENTRY_SIZE || word(3) as usize != ACCESS_SIZE {
303 return Err(Error::Format(format!("{}: not a version-{VERSION} sideband file", path.display())));
304 }
305 Ok(SideReader { inp, vcpu: word(1) })
306 }
307
308 pub fn vcpu(&self) -> u32 {
310 self.vcpu
311 }
312}
313
314impl Iterator for SideReader {
315 type Item = Result<SideEntry>;
316 fn next(&mut self) -> Option<Result<SideEntry>> {
317 let mut b = [0u8; ENTRY_SIZE];
318 match self.inp.read_exact(&mut b) {
319 Ok(()) => {}
320 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return None,
321 Err(e) => return Some(Err(e.into())),
322 }
323 let u64_at = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap());
324 let n = u16::from_le_bytes([b[68], b[69]]) as usize;
325 let mut accesses = Vec::with_capacity(n);
326 for _ in 0..n {
327 let mut a = [0u8; ACCESS_SIZE];
328 if let Err(e) = self.inp.read_exact(&mut a) {
329 return Some(Err(e.into()));
330 }
331 accesses.push(SideAccess::from_bytes(&a));
332 }
333 Some(Ok(SideEntry {
334 raw_index: u64_at(0),
335 global_seq: u64_at(8),
336 local_seq: u64_at(16),
337 cr3: u64_at(24),
338 physical_pc: u64_at(32),
339 cs: u16::from_le_bytes([b[40], b[41]]),
340 flags: u16::from_le_bytes([b[42], b[43]]),
341 cpl: b[44],
342 mode: b[45],
343 outcome: b[46],
344 vector: b[47],
345 len: b[48],
346 bytes: b[49..64].try_into().unwrap(),
347 vcpu: u32::from_le_bytes(b[64..68].try_into().unwrap()),
348 accesses,
349 }))
350 }
351}