Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 31 additions & 5 deletions crates/boards/src/peripheral.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use orchard_cache::store::sha256;
use orchard_cache::{Code, Context, Error, Result};
use orchard_formats::kernelcache::{self, Kernelcache};
use orchard_formats::z2fw::{self, Bootloader, Gen1, Profile, N1};
use orchard_formats::{aop, bluetool, cs42l75, dyld_cache, im4p, isp_setfile, sgx, trx};
use orchard_formats::{aop, bluetool, cs42l75, dyld_cache, h4isp, im4p, isp_setfile, sgx, trx};
use std::collections::HashMap;
use std::path::{Component, Path};

Expand Down Expand Up @@ -49,6 +49,10 @@ enum Step {
module: String,
data: String,
},
/// Firmware or one module set-file from the armv7s H4ISPServices image.
H4isp {
module: Option<String>,
},
/// The CS42L75 codec's speaker protection firmware, from the IM4P
/// payload of `<board>_CallanFirmware.im4p`.
Cs42l75Clp,
Expand Down Expand Up @@ -208,9 +212,11 @@ impl<'a> Plan<'a> {
let mut written = Vec::new();
let mut kernels = HashMap::new();
let mut setfiles = Setfiles::new(&self.build);
let mut cameras = HashMap::new();
for (output, steps) in &self.build {
let dest = &output.destination;
let bytes = run(output, steps, inputs, &mut kernels, &mut setfiles).context(dest)?;
let bytes = run(output, steps, inputs, &mut kernels, &mut setfiles, &mut cameras)
.context(dest)?;
let actual = sha256(&bytes);
if let Check::Sha256(expected) = &output.check {
if !actual.eq_ignore_ascii_case(expected) {
Expand Down Expand Up @@ -294,12 +300,22 @@ fn run(
inputs: &mut Inputs,
kernels: &mut Kernels,
setfiles: &mut Setfiles,
cameras: &mut HashMap<String, h4isp::Services>,
) -> Result<Vec<u8>> {
let first = output.steps[0].input.as_deref().unwrap_or_default();
let mut data = match steps.first() {
// The armv7s cache exceeds the normal file limit. Read it once per input,
// then retain only the two H4ISP sections for the other sensor modules.
let (mut data, steps) = match steps.split_first() {
Some((Step::H4isp { module }, rest)) => {
if !cameras.contains_key(first) {
let cache = inputs.get(first, MAX_DYLD_CACHE)?.bytes;
cameras.insert(first.to_owned(), h4isp::Services::from_cache(&cache)?);
}
(cameras[first].output(module.as_deref())?.to_vec(), rest)
}
// Read once for all outputs, through `setfiles`.
Some(Step::IspSetfile { .. }) => Vec::new(),
_ => inputs.get(first, MAX_FILE)?.bytes,
Some((Step::IspSetfile { .. }, _)) => (Vec::new(), steps),
_ => (inputs.get(first, MAX_FILE)?.bytes, steps),
};
for step in steps {
data = match step {
Expand Down Expand Up @@ -385,6 +401,9 @@ fn run(
}
payload.to_vec()
}
Step::H4isp { module } => h4isp::Services::from_cache(&data)?
.output(module.as_deref())?
.to_vec(),
Step::Gunzip => gunzip(&data, MAX_FILE)?,
};
}
Expand Down Expand Up @@ -659,6 +678,13 @@ fn parse(raw: &catalog::Step, recipe: &Recipe) -> Result<Option<Step>> {
&["build"],
),
"im4p-payload@1" => (Step::Im4pPayload, &[]),
"h4isp-from-services@1" if raw.params.contains_key("module") => (
Step::H4isp {
module: Some(string("module")?),
},
&["module"],
),
"h4isp-from-services@1" => (Step::H4isp { module: None }, &[]),
"gunzip@1" => (Step::Gunzip, &[]),
"isp-setfiles-from-dyld-cache@1" => {
let module = string("module")?;
Expand Down
175 changes: 175 additions & 0 deletions crates/formats/src/h4isp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
//! Camera firmware in the iOS 8 H4ISPServices image in the armv7s dyld shared cache.
use crate::{Error, Result};

const IMAGE: &[u8] = b"/System/Library/PrivateFrameworks/H4ISPServices.framework/H4ISPServices\0";
const FIRMWARE_SIZE: usize = 0x158004;
const LC_SEGMENT: u32 = 1;

// H4ISPServices' module selector supplies these offsets and lengths within H4ISPSETFILE.
// The gaps between modules are alignment padding, which the driver must not receive.
const SETFILES: &[(&str, usize, usize)] = &[
("8111_01XX", 0x00000, 0x831c),
("8112_01XX", 0x09000, 0x831c),
("8121_01XX", 0x12000, 0x831c),
("8122_01XX", 0x1b000, 0x831c),
("8411_01XX", 0x24000, 0x839c),
("8421_01XX", 0x2d000, 0x839c),
("8413_01XX", 0x36000, 0x839c),
("8423_01XX", 0x3f000, 0x839c),
("5213_01XX", 0x48000, 0x7690),
("5212_01XX", 0x50000, 0x7690),
("5223_01XX", 0x58000, 0x7690),
("5222_01XX", 0x60000, 0x7690),
("6921_01XX", 0x68000, 0x7764),
("6922_01XX", 0x70000, 0x7764),
("6521_01XX", 0x78000, 0x7764),
("6522_01XX", 0x80000, 0x7764),
("1011_04XX", 0x88000, 0x4efc),
("1032_04XX", 0x8d000, 0x4efc),
("1031_04XX", 0x92000, 0x4efc),
("0011_01XX", 0x97000, 0x4840),
("0022_02XX", 0x9c000, 0x4840),
("2111_01XX", 0xa1000, 0x4840),
("2122_02XX", 0xa6000, 0x4840),
("0211_01XX", 0xab000, 0x4840),
("0221_01XX", 0xb0000, 0x4840),
("0222_02XX", 0xb5000, 0x4840),
("4413_02XX", 0xba000, 0x583c),
("4441_02XX", 0xc0000, 0x583c),
("7651_01XX", 0xc6000, 0x578c),
("7652_01XX", 0xcc000, 0x578c),
("7653_01XX", 0xd2000, 0x578c),
];

fn word(data: &[u8], offset: usize) -> Result<u32> {
let bytes = data
.get(offset..offset + 4)
.ok_or(Error("truncated H4ISPServices header"))?;
Ok(u32::from_le_bytes(bytes.try_into().unwrap()))
}

fn quad(record: &[u8], offset: usize) -> u64 {
// All callers have a complete 32-byte dyld record.
u64::from_le_bytes(record[offset..offset + 8].try_into().unwrap())
}

fn span(data: &[u8], start: u64, len: u64) -> Result<&[u8]> {
let end = start
.checked_add(len)
.filter(|&n| n <= data.len() as u64)
.ok_or(Error("H4ISPServices range outside its file"))?;
Ok(&data[start as usize..end as usize])
}

/// The two sections retained from the cache, shared by every output of this input.
pub struct Services {
firmware: Vec<u8>,
setfiles: Vec<u8>,
}

impl Services {
pub fn from_cache(cache: &[u8]) -> Result<Self> {
if !cache.starts_with(b"dyld_v1 armv7s\0") {
return Err(Error("expected an armv7s dyld shared cache"));
}
let records = |at| -> Result<_> {
let start = u64::from(word(cache, at)?);
let count = u64::from(word(cache, at + 4)?);
Ok(span(cache, start, count * 32)?.chunks_exact(32))
};
let images = records(0x18)?;
let mut header = None;
for image in images {
let path = word(image, 24)? as usize;
if cache.get(path..).is_some_and(|s| s.starts_with(IMAGE))
&& header.replace(quad(image, 0)).is_some()
{
return Err(Error("duplicate H4ISPServices image"));
}
}
let header = header.ok_or(Error("no H4ISPServices in the dyld cache"))?;
let mappings = records(0x10)?;
let read = |addr: u64, len: u64| {
for mapping in mappings.clone() {
let Some(delta) = addr.checked_sub(quad(mapping, 0)) else {
continue;
};
if delta
.checked_add(len)
.is_some_and(|end| end <= quad(mapping, 8))
{
let off = quad(mapping, 16)
.checked_add(delta)
.ok_or(Error("bad dyld mapping"))?;
return span(cache, off, len);
}
}
Err(Error("H4ISPServices address outside dyld mappings"))
};

let mh = read(header, 28)?;
if word(mh, 0)? != 0xfeedface || word(mh, 4)? != 12 {
return Err(Error("expected a 32-bit ARM H4ISPServices image"));
}
let size = u64::from(word(mh, 20)?);
let mut commands = &read(header, 28 + size)?[28..];
let (mut firmware, mut setfiles) = (None, None);
for _ in 0..word(mh, 16)? {
let len = word(commands, 4)? as usize;
if len < 8 || len > commands.len() {
return Err(Error("bad H4ISPServices load command size"));
}
let (cmd, rest) = commands.split_at(len);
commands = rest;
if word(cmd, 0)? != LC_SEGMENT {
continue;
}
let count = u64::from(word(cmd, 48)?);
let sections = span(cmd, 56, count * 68)?;
if &cmd[8..24] != b"__DATA\0\0\0\0\0\0\0\0\0\0" {
continue;
}
for section in sections.chunks_exact(68) {
let slot = match &section[..16] {
b"H4ISPFIRMWARE\0\0\0" => &mut firmware,
b"H4ISPSETFILE\0\0\0\0" => &mut setfiles,
_ => continue,
};
let bytes = read(u64::from(word(section, 32)?), u64::from(word(section, 36)?))?;
if slot.replace(bytes).is_some() {
return Err(Error("duplicate H4ISPServices section"));
}
}
}
let firmware = firmware.ok_or(Error("missing H4ISPFIRMWARE"))?;
if firmware.len() != FIRMWARE_SIZE || &firmware[0x1040..0x1043] != b"adc" {
return Err(Error("bad H4ISPFIRMWARE size or header"));
}
let setfiles = setfiles.ok_or(Error("missing H4ISPSETFILE"))?;
if setfiles.len() != 0xd778c {
return Err(Error("bad H4ISPSETFILE size"));
}
Ok(Self {
firmware: firmware.to_vec(),
setfiles: setfiles.to_vec(),
})
}

/// The firmware when the module is omitted, otherwise the named sensor module's set-file.
pub fn output(&self, module: Option<&str>) -> Result<&[u8]> {
let Some(module) = module else {
return Ok(&self.firmware);
};
let &(name, offset, len) = SETFILES
.iter()
.find(|&&(name, _, _)| name == module)
.ok_or(Error("unknown H4ISP set-file module"))?;
let bytes = span(&self.setfiles, offset as u64, len as u64)?;
// The three bytes are the two sensor/module bytes and the revision in the iOS name.
let header = [0, 2, 5].map(|i| u8::from_str_radix(&name[i..i + 2], 16).unwrap());
if !bytes.starts_with(&header) {
return Err(Error("H4ISP set-file header disagrees with module name"));
}
Ok(bytes)
}
}
1 change: 1 addition & 0 deletions crates/formats/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod fat32;
pub mod fat32_read;
pub mod fdt;
pub mod gpt;
pub mod h4isp;
pub mod hfs;
pub mod hfs_write;
pub mod iboot;
Expand Down
77 changes: 76 additions & 1 deletion crates/formats/tests/steps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! are what orchard's Python extractors gave for them before they went.
use orchard_formats::kernelcache::{self, Kernelcache};
use orchard_formats::z2fw::{self, Profile, N1};
use orchard_formats::{bluetool, sgx};
use orchard_formats::{bluetool, h4isp, sgx};
use sha2::{Digest, Sha256};

fn sha256(bytes: &[u8]) -> String {
Expand Down Expand Up @@ -125,3 +125,78 @@ fn smartio_of_a_kext_merged_into_the_kernel() {
assert!(kernelcache::smartio(&cache, "com.apple.driver.Other").is_err());
assert_eq!(kernelcache::SMARTIO_KEXTS.len(), 7);
}

#[test]
fn h4isp_firmware_and_module_from_the_armv7s_shared_cache() {
fn put(buf: &mut [u8], at: usize, n: u32) {
buf[at..at + 4].copy_from_slice(&n.to_le_bytes());
}
const PATH: &[u8] =
b"/System/Library/PrivateFrameworks/H4ISPServices.framework/H4ISPServices\0";
// The test cache has separate text and data mappings with different slides.
const HEADER: usize = 0x200;
const DATA: usize = 0x1000;
const DATA_VM: u32 = 0x30000000;
const FW: usize = 0x158004;
const SETS: usize = 0xd778c;
let mut cache = vec![0; DATA + FW + SETS];
cache[..16].copy_from_slice(b"dyld_v1 armv7s\0");
for (at, n) in [
(16, 0x40),
(20, 2),
(24, 0x80),
(28, 1),
(0x40, 0x20000000),
(0x48, DATA as u32),
(0x60, DATA_VM),
(0x68, (FW + SETS) as u32),
(0x70, DATA as u32),
(0x80, 0x20000000 + HEADER as u32),
(0x98, 0xa0),
] {
put(&mut cache, at, n);
}
cache[0xa0..0xa0 + PATH.len()].copy_from_slice(PATH);
let command = HEADER + 28;
let mh = &mut cache[HEADER..];
put(mh, 0, 0xfeedface);
put(mh, 4, 12);
put(mh, 16, 1);
put(mh, 20, 56 + 2 * 68);
let seg = &mut cache[command..];
put(seg, 0, 1);
put(seg, 4, 56 + 2 * 68);
seg[8..14].copy_from_slice(b"__DATA");
put(seg, 24, DATA_VM);
put(seg, 28, (FW + SETS) as u32);
put(seg, 48, 2);
for (at, name, addr, size) in [
(56, b"H4ISPFIRMWARE".as_slice(), DATA_VM, FW),
(
56 + 68,
b"H4ISPSETFILE".as_slice(),
DATA_VM + FW as u32,
SETS,
),
] {
seg[at..at + name.len()].copy_from_slice(name);
seg[at + 16..at + 22].copy_from_slice(b"__DATA");
put(seg, at + 32, addr);
put(seg, at + 36, size as u32);
}
cache[DATA + 0x1040..DATA + 0x1043].copy_from_slice(b"adc");
let start = DATA + FW + 0x9000;
cache[start..start + 0x831c].fill(0xa5);
cache[start..start + 3].copy_from_slice(&[0x81, 0x12, 0x01]);
let services = h4isp::Services::from_cache(&cache).unwrap();
assert_eq!(services.output(None).unwrap(), &cache[DATA..DATA + FW]);
assert_eq!(
services.output(Some("8112_01XX")).unwrap(),
&cache[start..start + 0x831c]
);
assert!(services.output(Some("8111_01XX")).is_err()); // wrong module header
assert!(services.output(Some("unknown")).is_err());
assert!(h4isp::Services::from_cache(&cache[..cache.len() - 1]).is_err());
cache[DATA + 0x1040] = 0;
assert!(h4isp::Services::from_cache(&cache).is_err());
}
Loading