1mod compression;
26mod container;
27mod discovery;
28mod extract;
29mod fileset;
30mod fixups;
31mod lookup;
32mod prelink;
33mod reader;
34mod strings;
35
36pub use compression::Compression;
37pub use container::Container;
38pub use discovery::{
39 CollectionIdentity, DiscoveryCommand, KernelCandidate, KernelDiscoveryReport, KernelUuid,
40 discover_kernelcaches,
41};
42
43use std::collections::HashSet;
44use std::fmt;
45use std::fs;
46use std::path::Path;
47use std::sync::OnceLock;
48
49use crate::error::{Error, Result};
50use crate::macho::{MH_EXECUTE, MH_FILESET, MH_MAGIC, MH_MAGIC_64, MachOContext, SegmentInfo};
51
52use fixups::Rebase;
53use reader::{read_u32, slice, to_usize};
54
55const MAX_SIZE: usize = 1 << 30;
57
58const MACH_HEADER_SIZE: usize = 28;
60const MACH_HEADER_64_SIZE: usize = 32;
61const SIZEOFCMDS_OFFSET: usize = 20;
63
64pub const KERNEL_IMAGE_ID: &str = "com.apple.kernel";
66
67const LINKEDIT_SEGMENT: &str = "__LINKEDIT";
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum KernelCacheFormat {
77 Fileset,
79 Prelinked,
81}
82
83impl fmt::Display for KernelCacheFormat {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 f.write_str(match self {
86 Self::Fileset => "fileset (MH_FILESET)",
87 Self::Prelinked => "prelinked (MH_EXECUTE)",
88 })
89 }
90}
91
92#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94pub struct InputEncoding {
95 pub container: Option<Container>,
97 pub compression: Option<Compression>,
99}
100
101#[derive(Debug)]
105pub struct KernelImage {
106 pub id: String,
108 pub address: u64,
110 pub file_offset: u64,
112 pub macho: MachOContext,
114 offset_base: OffsetBase,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119enum OffsetBase {
120 Collection,
122 Image,
124}
125
126impl KernelImage {
127 pub fn segment_containing(&self, address: u64) -> Option<&SegmentInfo> {
129 self.macho
130 .segments()
131 .find(|segment| segment.name() != LINKEDIT_SEGMENT && vm_contains(segment, address))
132 }
133
134 fn local_header_offset(&self) -> u64 {
136 match self.offset_base {
137 OffsetBase::Collection => self.file_offset,
138 OffsetBase::Image => 0,
139 }
140 }
141}
142
143#[derive(Debug)]
145pub struct KernelCacheContext {
146 data: Vec<u8>,
148 encoding: InputEncoding,
149 pub macho: MachOContext,
151 pub images: Vec<KernelImage>,
153 rebases: OnceLock<std::result::Result<Vec<Rebase>, (usize, String)>>,
156}
157
158impl KernelCacheContext {
163 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
167 let path = path.as_ref();
168 if fs::metadata(path)?.len() > MAX_SIZE as u64 {
169 return Err(Error::parse(0, "kernelcache input exceeds 1 GiB"));
170 }
171 Self::from_vec(fs::read(path)?)
172 }
173
174 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
176 Self::from_vec(bytes.to_vec())
177 }
178
179 fn from_vec(input: Vec<u8>) -> Result<Self> {
180 if input.len() > MAX_SIZE {
181 return Err(Error::parse(0, "kernelcache input exceeds 1 GiB"));
182 }
183 let (data, encoding) = decode_input(input)?;
184 let macho = parse_macho_at(&data, 0)?;
185 for segment in macho.segments() {
186 check_segment_extent(segment, "outer")?;
187 let command = &segment.command;
188 if command.filesize != 0 {
189 slice(
190 &data,
191 to_usize(command.fileoff)?,
192 to_usize(command.filesize)?,
193 )?;
194 }
195 }
196 let images = match macho.header.filetype {
197 MH_FILESET => fileset::read_images(&data, &macho)?,
198 MH_EXECUTE if macho.segment(prelink::PRELINK_INFO_SEGMENT).is_some() => {
199 prelink::read_images(&data, &macho)?
200 }
201 _ => {
202 return Err(Error::parse(
203 0,
204 "expected MH_FILESET or a prelinked MH_EXECUTE kernel",
205 ));
206 }
207 };
208 let cache = Self {
209 data,
210 encoding,
211 macho,
212 images,
213 rebases: OnceLock::new(),
214 };
215 cache.validate_images()?;
216 Ok(cache)
217 }
218
219 fn validate_images(&self) -> Result<()> {
221 let mut ids = HashSet::with_capacity(self.images.len());
222 for image in &self.images {
223 if !ids.insert(image.id.as_str()) {
224 return Err(Error::parse(
225 0,
226 format!("duplicate kernelcache image ID {:?}", image.id),
227 ));
228 }
229 if image.macho.header.cputype != self.macho.header.cputype {
230 return Err(Error::parse(0, "embedded CPU type differs from collection"));
231 }
232 for segment in image.macho.segments() {
233 check_segment_extent(segment, "member")?;
234 let command = &segment.command;
235 for section in &segment.sections {
236 let within_segment = section
237 .section
238 .addr
239 .checked_sub(command.vmaddr)
240 .and_then(|start| start.checked_add(section.section.size))
241 .is_some_and(|end| end <= command.vmsize);
242 if section.section.size != 0 && !within_segment {
243 return Err(Error::parse(
244 section.struct_offset,
245 "section extends beyond segment VM range",
246 ));
247 }
248 }
249 if command.filesize != 0 {
250 self.member_bytes(image, command.fileoff, command.filesize)?;
251 }
252 }
253 }
254 Ok(())
255 }
256}
257
258fn decode_input(input: Vec<u8>) -> Result<(Vec<u8>, InputEncoding)> {
260 let (container, payload) = match container::unwrap(&input)? {
261 Some((container, payload)) => (Some(container), payload),
262 None => (None, input.as_slice()),
263 };
264 let compression = Compression::detect(payload);
265 let encoding = InputEncoding {
266 container,
267 compression,
268 };
269 let data = match compression {
270 Some(compression) => compression.decompress(payload)?,
271 None if container.is_some() => payload.to_vec(),
272 None => input,
273 };
274 Ok((data, encoding))
275}
276
277fn parse_macho_at(data: &[u8], offset: usize) -> Result<MachOContext> {
281 let header_size = match read_u32(data, offset)? {
282 MH_MAGIC => MACH_HEADER_SIZE,
283 MH_MAGIC_64 => MACH_HEADER_64_SIZE,
284 magic => return Err(Error::InvalidMachoMagic(magic)),
285 };
286 let header = slice(data, offset, header_size)?;
287 let commands_size = read_u32(header, SIZEOFCMDS_OFFSET)? as usize;
288 let macho = MachOContext::new(slice(data, offset, header_size + commands_size)?, offset)?;
289 let parsed_size: usize = macho
290 .load_commands
291 .iter()
292 .map(|command| command.size() as usize)
293 .sum();
294 if parsed_size != commands_size {
295 return Err(Error::parse(offset, "load command count and size disagree"));
296 }
297 Ok(macho)
298}
299
300fn check_segment_extent(segment: &SegmentInfo, scope: &str) -> Result<()> {
302 let command = &segment.command;
303 if command.vmaddr.checked_add(command.vmsize).is_none() {
304 return Err(Error::parse(
305 0,
306 format!("{scope} segment {} VM range overflow", segment.name()),
307 ));
308 }
309 if command.filesize > command.vmsize {
310 return Err(Error::parse(
311 0,
312 format!(
313 "{scope} segment {} file size exceeds VM size",
314 segment.name()
315 ),
316 ));
317 }
318 Ok(())
319}
320
321fn vm_contains(segment: &SegmentInfo, address: u64) -> bool {
323 address
324 .checked_sub(segment.command.vmaddr)
325 .is_some_and(|delta| delta < segment.command.vmsize)
326}
327
328impl KernelCacheContext {
333 pub fn format(&self) -> KernelCacheFormat {
335 if self.macho.header.filetype == MH_FILESET {
336 KernelCacheFormat::Fileset
337 } else {
338 KernelCacheFormat::Prelinked
339 }
340 }
341
342 pub fn encoding(&self) -> InputEncoding {
344 self.encoding
345 }
346
347 pub fn architecture(&self) -> &str {
349 self.macho.header.arch_name()
350 }
351
352 pub fn total_size(&self) -> usize {
354 self.data.len()
355 }
356
357 pub fn resolve_image(&self, query: &str) -> Result<&KernelImage> {
362 if let Some(image) = self.images.iter().find(|image| image.id == query) {
363 return Ok(image);
364 }
365 let candidates: Vec<_> = self
366 .images
367 .iter()
368 .filter(|image| image.id.contains(query))
369 .collect();
370 match candidates.as_slice() {
371 [image] => Ok(image),
372 [] => Err(Error::ImageNotFound { name: query.into() }),
373 _ => Err(Error::AmbiguousImage {
374 query: query.into(),
375 candidates: candidates.iter().map(|image| image.id.clone()).collect(),
376 }),
377 }
378 }
379
380 fn member_offset(&self, image: &KernelImage, offset: u64) -> Result<usize> {
382 let offset = match image.offset_base {
383 OffsetBase::Collection => Some(offset),
384 OffsetBase::Image => offset.checked_add(image.file_offset),
385 };
386 to_usize(offset.ok_or_else(|| Error::parse(0, "member file offset overflow"))?)
387 }
388
389 fn member_bytes(&self, image: &KernelImage, offset: u64, size: u64) -> Result<&[u8]> {
391 slice(
392 &self.data,
393 self.member_offset(image, offset)?,
394 to_usize(size)?,
395 )
396 }
397}