From 07d7633c6d143e9ea344f1cdbb56bfa2afffd707 Mon Sep 17 00:00:00 2001 From: Camden Bopp Date: Sat, 12 Sep 2026 14:10:06 -0400 Subject: [PATCH] Memoize the negative result of the lazy `cache` getter `MachOFile.cache` lazily loads the dyld shared cache the file belongs to via `try? DyldCache.init(url:)`, storing the result in `_cache`. For a standalone (non-cache) Mach-O the init fails and `_cache` stays nil, which is indistinguishable from "not yet attempted", so every subsequent `cache` access re-runs the init: another `open()`, mmap and URL-path resolution of the file, only to fail again. A consumer that touches `cache` once per symbol pays this per symbol. Building a Swift symbol index over a ~30 MB standalone binary (~45k local Swift symbols) spent ~8.5s of a 12.8s run re-opening the file as a dyld cache tens of thousands of times, all discarded. Memoize the negative result with a one-shot flag so the failed init runs at most once. `_cache`/`_fullCache` success paths are unchanged; a genuine cache image still resolves and caches on first touch. Behavior is identical, only repeated failed loads are elided. Verified: byte-identical output from a downstream Swift metadata dumper across five fixture dylibs; the same dump on a 30 MB binary went 12.8s -> 4.3s and an interface reconstruction 19s -> 5.1s, with `DyldCache.init` dropping from ~99% of samples to absent in a sampling profile. --- Sources/MachOKit/MachOFile.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Sources/MachOKit/MachOFile.swift b/Sources/MachOKit/MachOFile.swift index 83d89cbe..73693021 100644 --- a/Sources/MachOKit/MachOFile.swift +++ b/Sources/MachOKit/MachOFile.swift @@ -29,6 +29,12 @@ public class MachOFile: MachORepresentable { // Retain the cache to which `self` belongs private var _fullCache: FullDyldCache? private var _cache: DyldCache? + // Memoizes whether the lazy `cache` getter has already tried + // `DyldCache.init(url:)`. A standalone (non-cache) MachOFile fails that + // init and leaves `_cache` nil, which is indistinguishable from "not yet + // attempted", so without this flag every `cache` access re-opens and + // re-parses the file from disk. + private var _cacheResolutionAttempted = false // Cache for chained fixups lookup private var _chainedFixupsCache: DyldChainedFixups? @@ -637,7 +643,9 @@ extension MachOFile { if let _fullCache { return _fullCache.cache(for: url) } + if _cacheResolutionAttempted { return nil } _cache = try? .init(url: url) + _cacheResolutionAttempted = true return _cache }