dylex 3.0.0

A high-performance dyld shared cache and kernelcache extractor for macOS and iOS
Documentation
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Infer directly referenced runtime images without dependency-graph traversal.
use crate::{DyldContext, Error, MachOContext, Result, arm64, macho::*};
use std::collections::{BTreeMap, HashMap, HashSet};

/// Evidence for one directly referenced runtime image.
#[derive(Debug, Clone)]
pub struct RuntimeImageReference {
    /// Canonical path of the inferred image.
    pub image_path: String,
    /// Number of distinct branch/pointer sites in the selected roots.
    pub reference_count: usize,
    /// Source image for the first reference.
    pub source_image: String,
    /// Address of the first referring instruction or pointer slot.
    pub source_address: u64,
    /// Destination before following any stubs.
    pub via_address: u64,
    /// Final address inside the runtime image.
    pub target_address: u64,
}

fn invalid(reason: &str) -> Error {
    Error::Parse {
        offset: 0,
        reason: reason.into(),
    }
}

/// Runtime policy: libSystem components, Objective-C, C++, and Swift libraries.
/// Frameworks and arbitrary libraries are selected explicitly with --merge-image.
pub fn is_runtime_image(path: &str) -> bool {
    (path.starts_with("/usr/lib/system/") && path.ends_with(".dylib"))
        || matches!(
            path,
            "/usr/lib/libSystem.B.dylib"
                | "/usr/lib/libobjc.A.dylib"
                | "/usr/lib/libc++.1.dylib"
                | "/usr/lib/libc++abi.dylib"
        )
        || (path.starts_with("/usr/lib/swift/libswift") && path.ends_with(".dylib"))
}

struct Range {
    start: u64,
    end: u64,
    image: usize,
}
struct Ownership {
    ranges: Vec<Range>,
    prefix_end: Vec<u64>,
    stubs: Vec<(u64, u64)>,
    stub_prefix_end: Vec<u64>,
}
impl Ownership {
    fn new(cache: &DyldContext) -> Result<Self> {
        let mut ranges = Vec::new();
        let mut stubs = Vec::new();
        for (index, image) in cache.images.iter().enumerate() {
            for segment in cache
                .image_header(image.address)?
                .segments()
                .filter(|s| s.name() != "__LINKEDIT")
            {
                let start = segment.command.vmaddr;
                let end = start
                    .checked_add(segment.command.vmsize)
                    .ok_or_else(|| invalid("image VM extent overflow"))?;
                if start != end {
                    ranges.push(Range {
                        start,
                        end,
                        image: index,
                    });
                }
                for section in &segment.sections {
                    if section.section.flags & SECTION_TYPE == S_SYMBOL_STUBS
                        || matches!(section.name(), "__stubs" | "__auth_stubs" | "__objc_stubs")
                    {
                        let a = section.section.addr;
                        let b = a
                            .checked_add(section.section.size)
                            .ok_or_else(|| invalid("stub section extent overflow"))?;
                        if a < start || b > end {
                            return Err(invalid("stub section outside segment"));
                        }
                        if a != b {
                            stubs.push((a, b));
                        }
                    }
                }
            }
        }
        ranges.sort_by_key(|r| (r.start, r.image));
        let mut end = 0;
        let prefix_end = ranges
            .iter()
            .map(|r| {
                end = end.max(r.end);
                end
            })
            .collect();
        stubs.sort_unstable();
        let mut end = 0;
        let stub_prefix_end = stubs
            .iter()
            .map(|(_, b)| {
                end = end.max(*b);
                end
            })
            .collect();
        Ok(Self {
            ranges,
            prefix_end,
            stubs,
            stub_prefix_end,
        })
    }
    fn owner(&self, address: u64) -> Option<usize> {
        let mut i = self.ranges.partition_point(|r| r.start <= address);
        let mut owner = None;
        // Prefix maxima also handle image aliases/overlapping marker ranges;
        // retain cache-table order, matching ordinary address lookup.
        while i != 0 && self.prefix_end[i - 1] > address {
            i -= 1;
            let r = &self.ranges[i];
            if address < r.end {
                owner = Some(owner.map_or(r.image, |old: usize| old.min(r.image)));
            }
        }
        owner
    }
    fn is_stub(&self, address: u64) -> bool {
        let end = self.stubs.partition_point(|(a, _)| *a <= address);
        end != 0 && self.stub_prefix_end[end - 1] > address
    }
}

fn resolve_target(
    cache: &DyldContext,
    ownership: &Ownership,
    start: u64,
) -> Result<Option<(usize, u64)>> {
    let mut address = start;
    let mut seen = HashSet::new();
    for _ in 0..64 {
        if !seen.insert(address) {
            return Ok(None);
        }
        if let Some(index) = ownership.owner(address) {
            if is_runtime_image(&cache.images[index].path) {
                return Ok(Some((index, address)));
            }
            // An ordinary function in another image is not a trampoline just
            // because its first instruction branches into a runtime library.
            if !ownership.is_stub(address) {
                return Ok(None);
            }
            let Some(mapping) = cache
                .mapping_for_addr(address)
                .filter(|m| m.is_executable())
            else {
                return Ok(None);
            };
            let size = (mapping.size - (address - mapping.address)).min(16) as usize;
            let Some(stub) =
                super::decode_stub_for_cache(cache, cache.data_at_addr(address, size)?, address)
            else {
                return Ok(None);
            };
            address = if stub.indirect {
                cache.pointer_at(stub.target)?
            } else {
                stub.target
            };
        } else if let Some((target, _)) = cache.cache_stub_target(address)? {
            address = target;
        } else {
            return Ok(None);
        }
    }
    Ok(None)
}

fn pointer_section(section: &Section64) -> bool {
    matches!(
        section.flags & SECTION_TYPE,
        S_NON_LAZY_SYMBOL_POINTERS
            | S_LAZY_SYMBOL_POINTERS
            | S_LAZY_DYLIB_SYMBOL_POINTERS
            | S_THREAD_LOCAL_VARIABLE_POINTERS
    ) || matches!(
        section.name(),
        "__got" | "__auth_got" | "__la_symbol_ptr" | "__nl_symbol_ptr"
    )
}

// Mode evidence comes from mapped and omitted Mach-O symbols, never a blanket
// assumption that every ARMv7 instruction section contains Thumb code.
fn arm_code_modes(
    cache: &DyldContext,
    header: &MachOContext,
    address: u64,
) -> Result<BTreeMap<u64, bool>> {
    let mut symbols = Vec::new();
    if let Some(table) = header.symtab().filter(|s| s.nsyms != 0) {
        let link = header
            .linkedit_segment()
            .ok_or_else(|| invalid("ARM symbols without LINKEDIT"))?;
        let size = table
            .nsyms
            .checked_mul(12)
            .ok_or_else(|| invalid("ARM symbol table overflow"))? as u64;
        let delta = (table.symoff as u64)
            .checked_sub(link.command.fileoff)
            .filter(|d| {
                d.checked_add(size)
                    .is_some_and(|end| end <= link.command.filesize)
            })
            .ok_or_else(|| invalid("ARM symbols outside LINKEDIT"))?;
        for raw in cache
            .data_at_addr(link.command.vmaddr + delta, size as usize)?
            .chunks_exact(12)
        {
            symbols.push(read_nlist(raw, false)?);
        }
    }
    symbols.extend(
        cache
            .local_symbols_for_image(address)?
            .into_iter()
            .map(|s| s.entry),
    );
    let sections: Vec<_> = header.segments().flat_map(|s| &s.sections).collect();
    let mut modes = BTreeMap::new();
    for symbol in symbols {
        if symbol.n_type & N_STAB != 0 || symbol.n_type & N_TYPE != N_SECT || symbol.n_sect == 0 {
            continue;
        }
        let Some(section) = sections.get(symbol.n_sect as usize - 1) else {
            continue;
        };
        let s = &section.section;
        let pc = symbol.n_value & !1;
        if s.flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS) != 0
            && pc >= s.addr
            && pc - s.addr < s.size
        {
            modes.insert(
                pc,
                symbol.n_desc & N_ARM_THUMB_DEF != 0 || symbol.n_value & 1 != 0,
            );
        }
    }
    Ok(modes)
}

/// Infer runtime additions from the primary and explicitly selected images.
/// Scans ARM64 B/BL and symbol-mode-identified ARM/Thumb B/BL/BLX instructions
/// (excluding LC_DATA_IN_CODE spans), and declared pointer sections. Follows recognized
/// stubs for at most 64 hops. Newly inferred images are not scanned recursively.
/// Computed/register-only targets without static pointer evidence remain unknown.
pub fn referenced_runtime_images(
    cache: &DyldContext,
    roots: &[String],
) -> Result<Vec<RuntimeImageReference>> {
    let mut root_indexes = HashSet::new();
    for root in roots {
        let address = cache.resolve_image(root)?.address;
        root_indexes.extend(
            cache
                .images
                .iter()
                .filter(|image| image.address == address)
                .map(|image| image.index),
        );
    }
    let ownership = Ownership::new(cache)?;
    let mut results = BTreeMap::<String, RuntimeImageReference>::new();
    let mut resolved = HashMap::<u64, Option<(usize, u64)>>::new();
    let mut sites = HashSet::new();
    for root in roots {
        let image = cache.resolve_image(root)?;
        let header = cache.image_header(image.address)?;
        let arm_modes = if header.header.cputype == CPU_TYPE_ARM {
            arm_code_modes(cache, &header, image.address)?
        } else {
            BTreeMap::new()
        };
        let mut excluded = Vec::new();
        for lc in &header.load_commands {
            if let LoadCommandInfo::LinkeditData { command: c, .. } = lc {
                if c.cmd != LC_DATA_IN_CODE || c.datasize == 0 {
                    continue;
                }
                if c.datasize % 8 != 0 {
                    return Err(invalid("invalid data-in-code size"));
                }
                let link = header
                    .linkedit_segment()
                    .ok_or_else(|| invalid("no LINKEDIT for data-in-code"))?;
                let delta = (c.dataoff as u64)
                    .checked_sub(link.command.fileoff)
                    .filter(|d| {
                        d.checked_add(c.datasize as u64)
                            .is_some_and(|e| e <= link.command.filesize)
                    })
                    .ok_or_else(|| invalid("data-in-code outside LINKEDIT"))?;
                for entry in cache
                    .data_at_addr(link.command.vmaddr + delta, c.datasize as usize)?
                    .chunks_exact(8)
                {
                    let offset = u32::from_le_bytes(entry[..4].try_into().unwrap()) as u64;
                    let length = u16::from_le_bytes(entry[4..6].try_into().unwrap()) as u64;
                    let segment = header
                        .segments()
                        .find(|s| {
                            offset >= s.command.fileoff
                                && offset - s.command.fileoff < s.command.filesize
                        })
                        .ok_or_else(|| invalid("data-in-code outside source segments"))?;
                    let start = segment.command.vmaddr + offset - segment.command.fileoff;
                    let end = start
                        .checked_add(length)
                        .filter(|e| *e <= segment.command.vmaddr + segment.command.filesize)
                        .ok_or_else(|| invalid("data-in-code span outside segment"))?;
                    excluded.push((start, end));
                }
            }
        }
        excluded.sort_unstable();
        let mut record = |source_address, via_address| -> Result<()> {
            if !sites.insert((image.index, source_address)) {
                return Ok(());
            }
            let target = match resolved.get(&via_address) {
                Some(target) => *target,
                None => {
                    let target = resolve_target(cache, &ownership, via_address)?;
                    resolved.insert(via_address, target);
                    target
                }
            };
            let Some((index, target_address)) = target.filter(|(i, _)| !root_indexes.contains(i))
            else {
                return Ok(());
            };
            let path = &cache.images[index].path;
            results
                .entry(path.clone())
                .and_modify(|r| r.reference_count += 1)
                .or_insert_with(|| RuntimeImageReference {
                    image_path: path.clone(),
                    reference_count: 1,
                    source_image: image.path.clone(),
                    source_address,
                    via_address,
                    target_address,
                });
            Ok(())
        };
        for segment in header.segments().filter(|s| s.name() != "__LINKEDIT") {
            for item in &segment.sections {
                let s = &item.section;
                if s.size == 0 {
                    continue;
                }
                let delta = s.addr.checked_sub(segment.command.vmaddr).filter(|d| {
                    d.checked_add(s.size)
                        .is_some_and(|e| e <= segment.command.filesize)
                });
                if pointer_section(s) {
                    if delta.is_none()
                        || s.size % header.pointer_size() as u64 != 0
                        || s.addr % header.pointer_size() as u64 != 0
                    {
                        return Err(invalid("invalid pointer section extent/alignment"));
                    }
                    for offset in (0..s.size).step_by(header.pointer_size()) {
                        let address = s.addr + offset;
                        record(address, cache.pointer_at(address)?)?;
                    }
                } else if header.header.cputype == CPU_TYPE_ARM
                    && s.flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS) != 0
                {
                    if delta.is_none() {
                        return Err(invalid(
                            "ARM instruction section outside file-backed segment",
                        ));
                    }
                    let data = cache.data_at_addr(s.addr, s.size as usize)?;
                    let modes: Vec<_> = arm_modes
                        .range(s.addr..s.addr + s.size)
                        .map(|(&pc, &thumb)| (pc, thumb))
                        .collect();
                    for (i, &(start, thumb)) in modes.iter().enumerate() {
                        let end = modes.get(i + 1).map_or(s.addr + s.size, |(pc, _)| *pc);
                        let mut pc = start;
                        while pc < end {
                            let off = (pc - s.addr) as usize;
                            let rest = &data[off..(end - s.addr) as usize];
                            let size = if thumb {
                                crate::arm::thumb_instruction_size(rest)
                            } else {
                                (rest.len() >= 4).then_some(4)
                            };
                            let Some(size) = size else {
                                break;
                            };
                            if !excluded
                                .iter()
                                .any(|&(a, b)| pc < b && pc + size as u64 > a)
                            {
                                if let Some(target) =
                                    crate::arm::branch_target(rest, pc as u32, thumb)
                                {
                                    record(pc, target as u64)?;
                                }
                            }
                            pc += size as u64;
                        }
                    }
                } else if cache.architecture().starts_with("arm64")
                    && s.flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS) != 0
                {
                    if delta.is_none() || s.addr % 4 != 0 || s.size % 4 != 0 {
                        return Err(invalid(
                            "invalid ARM64 instruction section extent/alignment",
                        ));
                    }
                    let mut data = vec![
                        0;
                        usize::try_from(s.size)
                            .map_err(|_| invalid("instruction size overflow"))?
                    ];
                    cache.copy_data_at_addr(s.addr, &mut data)?;
                    for (i, word) in data.chunks_exact(4).enumerate() {
                        let pc = s.addr + i as u64 * 4;
                        if excluded.iter().any(|&(a, b)| pc < b && pc + 4 > a) {
                            continue;
                        }
                        let instruction = u32::from_le_bytes(word.try_into().unwrap());
                        if arm64::is_branch(instruction) {
                            record(pc, arm64::decode_branch(instruction, pc))?;
                        }
                    }
                }
            }
        }
    }
    Ok(results.into_values().collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn runtime_policy_is_explicit_and_directory_bounded() {
        for p in [
            "/usr/lib/system/libdispatch.dylib",
            "/usr/lib/libobjc.A.dylib",
            "/usr/lib/libc++.1.dylib",
            "/usr/lib/swift/libswiftCore.dylib",
        ] {
            assert!(is_runtime_image(p));
        }
        for p in [
            "/System/Library/Frameworks/Foundation.framework/Foundation",
            "/usr/lib/libsqlite3.dylib",
            "/usr/lib/systematic/libfoo.dylib",
            "/tmp/usr/lib/system/libc.dylib",
        ] {
            assert!(!is_runtime_image(p));
        }
    }
}