Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.

GitHub stars
339

Install

/plugin install swift-section@machoswiftsection

Run it inside Claude Code after adding the marketplace with /plugin marketplace add MxIris-Reverse-Engineering/MachOSwiftSection.

Contents

Discovered from source

Skills 1

swift-section

A CLI that reads Swift metadata straight out of a Mach-O file — the compiler-emitted __swift5_* sections plus the symbol table — and reconstructs source-level declarations from it. Nothing is loaded into a process and no source or .swiftmodule is needed, so it works on a stripped OS framework, a third-party app binary, or an image inside a dyld shared cache. Its objc subcommand does the same for the Objective-C metadata (§1).

Where it sits next to other reverse-engineering tools. It is the offline, scriptable form of the library RuntimeViewer uses. Reach for it when the target is a file rather than something loadable, when the build is not the one running on this machine (an archived cache, another OS version, another platform), or when the answer must be diffed or committed. swift-section recovers declarations, layout and addresses, never instruction-level behaviour: for what a method actually does, take its address from here (--emit-member-addresses, or the IMP comments of objc) and hand that address to a disassembler or decompiler opened on the same build. An address from one build means nothing in another.

0. Confirm the version before trusting a flag

The installed binary (brew install swift-section, on PATH) is often older than the repository, and flags are added frequently. Confirm before building a command line on one:

swift-section --version
swift-section interface --help | grep -- --exported-only    # empty ⇒ this build lacks it

Flags added comparatively late, and therefore worth checking: --emit-header, --emit-export-status, --exported-only, --jobs, evolution --interface, --supplementary-apinotes, from 0.20.0 --dependency-search-path, --infer-objc-overrides and the whole objc subcommand group, from 0.22.0 evolution --emit-available / --platform, from 0.23.0 interface --module-selectors / dump --enable-module-selectors, from 0.24.0 interface --requirements-on-associated-types and --emit-private-source-files, and from 0.25.0 objc evolution --interface / --emit-available / --platform, objc interface --swift, interface --no-existential-any / dump --disable-existential-any, interface --expand-macros and the refs and symbolicate subcommands. When one is missing, say so rather than silently producing a weaker answer — the alternative is usually "upgrade (brew upgrade swift-section), or do without that annotation".

1. Pick the subcommand

The questionSubcommand
What Swift types / protocols / conformances does this binary contain?dump
Give me something that reads like Swift source (or pastes into an editor)interface
What changed in the ABI between these two builds?diff
Freeze today's ABI so a future build can be compared without keeping the binarysnapshot
How did this API evolve across N OS versions?evolution
Reformat the memory-layout comments the two above emittransformer
Objective-C headers, IMP addresses, or an Objective-C API diff (0.20.0+, formerly the separate objc-section executable)objc — read references/objc.md first
Who calls this selector / symbol / function, who references this class, ivar or string — across a whole dyld shared cache or an app's filesrefs — read references/cross-references.md first
What is this address: which function and how far into it, a stub and where it leads, a slot and what it holdssymbolicate — same reference

dump is the default subcommand: swift-section <path> is swift-section dump <path>.

dump versus interface is not a cosmetic choice. dump walks the sections one by one and prints what each record literally says — descriptors, witness-table entries, associated types — in binary order if asked. interface builds a whole declaration model first: it indexes every symbol in the image, merges extensions, joins accessors to their vtable entries, recovers final / class keywords, and only then prints. That model is what makes the output readable, and it is also why interface costs orders of magnitude more (see §5). Start with dump to find out whether the type is even there; escalate to interface when you need to read it.

2. Pointing it at the binary

Three input shapes, and the option that selects each:

# 1. A file on disk. A fat (universal) binary REQUIRES an architecture — the tool
#    refuses to pick a slice and lists what it found.
swift-section dump /path/to/Foo.framework/Foo --architecture arm64e

# 2. An image inside the running system's shared cache (frameworks are not on disk
#    as separate files on modern macOS/iOS).
swift-section dump --uses-system-dyld-shared-cache --cache-image-name SwiftUICore

# 3. An image inside a specific cache file (an archived one, a simulator runtime's).
swift-section dump --dyld-shared-cache --cache-image-path /System/Library/.../SwiftUI /path/to/dyld_shared_cache
  • -n / --cache-image-name takes a bare image name (SwiftUICore); -p / --cache-image-path takes the install path. Pass exactly one — both together is an error. Prefer -p when a leaf name is ambiguous inside the cache (a macOS cache carries Mac Catalyst builds under /System/iOSSupport with the same leaf names).
  • diff and evolution read --dyld-shared-cache differently: it means "every input path is a cache, extract the same -n image from each". They have no --uses-system-dyld-shared-cache, and snapshot rejects it on purpose (a baseline needs a stable recorded path).
  • Neither -n nor -p does anything without one of the cache flags.
  • A standalone file's dependencies are looked for, not given. Some facts live in another image: a type behind a metadata accessor (an availability-conditional some View), a cross-module type's layout, an Objective-C superclass (override, explicit selectors). By default the tool infers paths from where the binary sits and falls back to the running system's cache — which never offers an image of another platform. So an iOS binary read on a macOS host needs --dependency-search-path (dump, interface, snapshot; repeatable) naming its runtime: a Mach-O file, a cache file (dyld_shared_cache_* / dyld_sim_shared_cache_*), or a directory used as a system root such as a simulator runtime's RuntimeRoot. Named paths are consulted before the running system's cache. An image read out of a cache (--dyld-shared-cache) needs none: it resolves in that same cache first, so an archived macOS 15 cache is laid out against its own Foundation, not the host's. When those facts are missing from an iOS binary's output, suspect this flag before the binary.

3. Never redirect interface's stdout — pass -o

interface writes its progress lines to stdout, mixed into the product:

$ swift-section interface -a arm64e /bin/ls > out.txt   # WRONG
$ head -3 out.txt
Preparing to build Swift interface...
[INFO] Extracted 0 symbol index
[INFO] Types: 0 successful, 0 failed, ...

Use --output-path / -o for anything that will be read back, diffed, or committed. The same holds for dump, whose per-declaration error lines also land on stdout — a dump redirect silently mixes Error: … lines into the product.

diff / snapshot / evolution are the well-behaved ones: progress and degradation diagnostics go to stderr, the report to stdout, so > is safe there. Their stderr chatter (dropped declarations, unresolved dependencies) is normal reporting, not failure — judge those runs by the exit code.

4. dump and interface do not share flag spellings

The single most common mistake. Same underlying comment, different name:

Commentdumpinterface
Field offsets--emit-field-offsets--emit-offset-comments (field and PWT offsets)
PWT addresses--emit-pwt-addressesfolded into the above

Spelled the same on both: --emit-type-layout, --emit-enum-layout, --emit-member-addresses, --emit-vtable-offsets, --emit-expanded-field-offsets (implies the field-offset flag), --emit-header, --emit-export-status, --emit-private-source-files, --color-scheme, --output-path, --dependency-search-path (§2).

--emit-private-source-files puts a comment above each declaration whose name carries a private discriminator, naming the source file the discriminator was derived from: // CodingKeys is declared in Codable.swift above enum Outer.(CodingKeys in _B89E…). The file is recovered by hashing candidate file names, so a named file is certain, but not every one is found; the rest read … could not be recovered (private discriminator _…). interface prints no discriminator anywhere else, so there this comment is what tells two same-named private types from different files apart. A member or nested type of a private type repeats nothing, since it is declared in that type's file. A private member of a public type names its own file, usually the file of the extension that declares it.

SE-0491 module selectors — Swift::Int instead of Swift.Int, the spelling a Swift 6.4 .swiftinterface uses, with every nested level naming the module that declared it (Swift::Duration.Foundation::TimeFormatStyle) — are off by default and spelled differently too: interface --module-selectors, dump --enable-module-selectors (one of the demangler switches below).

Existential types carry the any keyword by default in both outputs (from 0.25.0), as the compiler writes a .swiftinterface: any P, (any P)?, any P.Type for the existential metatype, (any P).Type for the metatype of the existential (older builds print P.Protocol), and any Any.Type — a lone Any or AnyObject stays bare. Older builds print every existential bare, so Swift.Collection in their output is any Collection. The off switches: interface --no-existential-any, dump --disable-existential-any. A stored property of a constrained existential type (any Boxed<Int>) printed in older builds as its arguments alone — var boxed: Swift.Int in interface, symbolic existential type … <Swift.Int> in dump — so read such a line from an older build as a constrained existential of unknown protocol, not as the type it names.

A class the @Observable macro expanded prints the way its source reads (from 0.25.0): @Observation.Observable above the class, each tracked property as the stored var x: T it was declared as, a stored var the macro left alone under @Observation.ObservationIgnored on a line of its own (a property wrapper's attribute gets a line of its own too), and no registrar, no access(keyPath:) / withMutation(keyPath:_:) / shouldNotifyObservers, no extension X: Observation.Observable {}. In the binary each tracked x is a computed property over private storage _x; interface --expand-macros prints that, as older builds always did. A tracked property whose accessors are stripped or dead-stripped (an internal class in an app or OS framework) carries a note naming the storage it was synthesized from; when nothing in the image names y or gives _y an initial value or accessors of its own, an @ObservationIgnored var _y reads as a tracked y behind such a note. SwiftData @Model classes are not folded. dump keeps every generated member and adds @Observation.Observable to the class's header line.

Only dump has: --sections, --preferred-binary-order, and the demangler option group (--demangle-options default|simplified|interface plus ~22 --enable-… / --disable-… switches).

Only interface has: --exported-only, --sort-members-by-offset, --parse-opaque-return-type, --show-c-imported-types, --resolve-c-module-names, --supplementary-apinotes, --infer-objc-overrides, --requirements-on-associated-types, --expand-macros.

--requirements-on-associated-types changes where a protocol's requirements print, never which: associatedtype Body: SwiftUI.View instead of protocol View where Self.Body: SwiftUI.View, the way the compiler writes a .swiftinterface. The binary keeps only the canonical requirement signature, so neither form says where the source wrote a requirement. One about an associated type of a refined protocol (Self.Element of a Sequence refinement) stays in the protocol's where clause either way, and diff / evolution always print that form.

--infer-objc-overrides is off by default for a reason. An override whose body the optimizer inlined into its thunk (viewDidHide, encodeWithCoder: in an OS framework) ties to no Swift symbol; the flag attributes it anyway, to the one member whose name is the importer's spelling of the selector. dump always shows such ties, marked (selector name, no symbol evidence); an interface has nowhere to say a keyword rests on a name, so it adds override only when asked.

--sections has two traps

swift-section dump --sections types,protocols /path/to/binary      # ERROR: comma is not a separator
swift-section dump --sections types protocols /path/to/binary      # ERROR: the path is eaten as a section
swift-section dump /path/to/binary --sections types protocols      # correct — path first
swift-section dump --sections types protocols -- /path/to/binary   # correct — `--` ends the list

It consumes values up to the next option, so the positional file path must not follow it. Both wrong forms above are the ones a comma-separated habit produces, and neither fails in an obvious way if you are skimming — read the error text. The habit is easy to pick up in this very executable: swift-section objc dump --sections is comma-separated (--sections classes,protocols).

Also: with no --sections, a section that is missing or unreadable is skipped silently — a binary with no Swift content produces zero output and exit status 0. Pass the section explicitly to get the diagnosis (Swift section __swift5_assocty not found …). So "empty output" never by itself means "no Swift in there"; confirm with an explicit --sections.

5. interface is expensive; dump is not

interface builds the whole image's demangled symbol index before printing anything. On a large system framework (SwiftUI, SwiftUICore) that is tens of seconds to minutes and a lot of resident memory. Budget for it:

  • Explore with dump (optionally --sections types) first; run interface once you know the target is there.
  • Never run interface over a whole dyld shared cache image set casually.
  • diff and evolution index every input, so cost multiplies by the number of versions. --jobs N bounds how many index at once (default: processor count); each in-flight input holds its indexed image in memory, so lower it when memory is the constraint, not 1 for speed's sake.
  • --emit-private-source-files searches every discriminator of the image once before the first declaration prints, and on dump it first indexes the image too, which dump otherwise never does. Measured on macOS 27.2 with a release build: SwiftUI's dump goes from 12 s to 58 s and its interface from 20 s to 61 s; Foundation's interface barely moves.
  • Anything long-running belongs in a background run written to a file with -o, not in a foreground command that will be waited on.

6. Comment templates

The five layout comment kinds (field offset, vtable offset, member address, type layout, enum layout) render from ${token} templates, and dump / interface accept the template options directly.

swift-section transformer templates --module field-offset   # names accepted by the options
swift-section transformer tokens --module enum-layout       # placeholders those templates take
  • A value containing ${ is a literal template; anything else must name a built-in template (matched case / space / hyphen / underscore insensitively). A name that matches nothing is a hard error, never a silently constant comment.
  • Passing any template option turns on the comment kind it formats — no separate --emit-… needed. The reverse does not hold.
  • --enum-layout-style is a whole-module preset: detailed (default) / explained (bit ranges in words) / standard / inline / compact.
  • swift-section transformer config … -o comments.json freezes a command line for reuse via --transformer-config; it is the same JSON shape RuntimeViewer persists.

7. diff / snapshot / evolution

swift-section diff old/Foo new/Foo                              # change list + verdict
swift-section diff old/Foo new/Foo --interface --format unified # annotated interface
swift-section snapshot /path/Foo --label 26.0 -o foo-26.0.json  # freeze a baseline
swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0
  • --json, --summary-only and --interface are mutually exclusive, and --format only applies with --interface.
  • --interface renders from live models, so every input must be a binary or cache — snapshot JSON is rejected there, though it is fine for the change-list / lineage reports.
  • evolution needs ≥ 2 inputs in version order, oldest first; --labels is comma-separated and must have exactly one label per input.
  • evolution --interface --emit-available adds a genuine @available(<platform>, introduced: …, obsoleted: …) line above each declaration whose whole lifecycle one attribute can express. No attribute is not "no lifecycle": a declaration that disappeared and came back, one that was only modified, or any involved label that is not a numeric version (the file-name fallback!) gets none — pass numeric --labels and read the // [●○●] comment, which is always there. The versions are axis points, not exact release versions. The platform is inferred from every input's LC_BUILD_VERSION (a simulator counts as its device); an input whose platform @available has no name for (DriverKit), or inputs of different platforms, fail with exit code 64 — name it with --platform (only valid with --emit-available, which is only valid with --interface).
  • --fail-on-breaking makes a breaking change a nonzero exit — that, not the report text, is the CI signal.
  • A version whose image carries no local Swift symbols cannot show non-exported members (SwiftUI in the macOS 13.0–14.8 caches is the case to know). It is detected per input, and such a member's absence there is never read as a removal: in evolution its bitmap position reads ◍ (not observable, but present in the versions on both sides — inferred) or ◌ (not observable, nothing claimed), a change across such versions is phrased removed between 12.7 and 15.0 / added between … (first observed at the later version, which is where it counts for the verdict), the interface legend names those versions, and a lifecycle whose ◌ span reaches an axis end or sits between different observations gets no @available (between two absences it keeps it). A member unseen only because its container is unseen carries no annotation of its own (read the container's); neither does one unseen only between two absences, which says nothing. diff lists what one side cannot show in a Not observable on the old/new side section (unobservableDeclarations in --json), never as removed or added and never breaking. Types, conformances, stored fields, enum cases and exported members stay observable, so their absence is still a real removal. diff --interface does not apply this.
  • Even so, compare binaries in similar strip states where you can. A symbol-rich build against a stripped one reports the same protocol requirement as a member swap, because a stripped protocol diffs by witness-table slot rather than by symbol.
  • A snapshot does not cross format versions. The JSON carries a formatVersion; any other version is rejected with a typed error, and the fix is to regenerate the baseline with the current tool. Format 6 (0.21.0 and later) rejects every format-5 baseline: in an image stripped of its local symbols the newer tool also records the class members that only their method descriptor names (see §9), which an old baseline would report as added wholesale. Format 7 (0.23.0 and later) rejects every format-6 baseline: a type declared in a function or closure body is recorded under its own full name now (see §9), and an old baseline would report each one as removed — a breaking change — and added again. Format 13 (0.25.0 and later) rejects every earlier baseline, for five reasons: in an optimized build the newer tool also records the members whose only symbol is their @objc thunk, their initializing entry point or that entry point's function signature specialization (see §9), which an old baseline would report as added; a snapshot now records whether its image keeps local Swift symbols and whether each member is exported, which the not-observable rule above needs; an image's extensions now hold the members of its own module's types that no definition in the image gathers — SwiftUI's members of the types SwiftUICore defines, an internal namespace whose type descriptor was stripped — which earlier tools left out of interface and the snapshot, and an old baseline would report as added (dump does not show them); a stored field whose type is a constrained existential (any Boxed<Int>) is recorded as that existential, where it used to read as its arguments alone, and an old baseline would report each such field as changed; and a property's SE-0400 init accessor is one of its accessors now, so an old baseline would report every property that has one as changed. Formats 8 through 12 only ever existed on the development branch, between those changes.

8. --resolve-c-module-names (interface, macOS only)

Turns __C.NSString into Foundation.NSString. Needs macOS 13+ and an Xcode installation, and the first run per SDK generates module interfaces through sourcekitd — slow once, cached after. Attribution against a non-macOS binary is limited (it warns and degrades rather than failing). --supplementary-apinotes only does anything alongside it.

9. Reading the output: things that look like bugs and are not

  • // not exported is an export-trie fact, not an access-level claim. A missing entry means "not statically callable from outside this image", which is not the same as internal.
  • … is declared in Enabled.swift of module SwiftUICore above a SwiftUI declaration is not a wrong module: the discriminator was hashed with the framework's own name, while its declarations print under their ABI module name (SwiftUI). could not be recovered means no candidate file name produced the digest; it says nothing about the declaration.
  • A type member printed static may have been class in the source: the four descriptor-less class spellings are ABI-identical to static, so the printer picks the spelling that is always legal.
  • Field offset: unknown (<reason>) is the layout engine declining to guess, and the reason names what it could not resolve. It is distinct from the flag being off (which emits nothing at all).
  • A generic type printed with unresolved fields is expected when no arguments were supplied: an unconstrained T has no layout until it is bound. Class-bound parameters and parameter metatypes do resolve unspecialized.
  • pwtslot: records in a protocol diff are the fallback view used when requirement symbols are stripped — see the strip-state warning in §7.
  • A class's members print in vtable slot order, not grouped by kind: for the class's own members that is the source's declaration order, so an init can sit between two methods. Only the members that own no slot (final, static, @objc dynamic, an ObjC-inherited init) follow, grouped by kind.
  • In an image stripped of its local symbols (AppKit in the OS dyld shared cache), a public class method may print without @objc or override. Its implementation symbol is gone (a library-evolution image exports only the dispatch thunk Tj and method descriptor Tq), so the member is rebuilt from the Tq symbol — the name and signature are exact, but the @objc / ObjC-override facts are joined through the implementation's symbol and are missing. A vtable slot nothing names (an internal member in a stripped image) is left out; dump lists it as sub_… or <unnamed vtable slot>.
  • In an optimized app binary, a member may print at the address of its @objc thunk, and an init at its initializing entry point or at that entry point's specialization. Whole-module optimization can inline an internal @objc member's body into its Objective-C thunk ($s…To) and delete the Swift entry point, and inline a class initializer's allocating entry point into its callers; Swift 6.4 also replaces the initializing entry point by its function signature specialization (…fcTf…), which takes its arguments differently. The member is then rebuilt from the code that survived: --emit-member-addresses points at the thunk, which uses the Objective-C calling convention (self in x0, _cmd in x1), at the initializing entry point, or at its specialization. dump lists the members only a thunk names under /* [ObjC Thunk] … */ sections.
  • A generic class, or one registered through __objc_stublist (its superclass is in another module, or is generic), has no class object, so its Objective-C method list comes from its Swift metadata. override is printed where its superclass chain can be followed. When the superclass is a Swift class of another binary (SwiftUI's NSHostingView<…>), the chain stops there and the class's members print with @objc but without override.
  • associatedtype Element without : ~Copyable / : ~Escapable does not prove the associated type is Copyable. The binary does not record that suppression (SE-0503); it is printed only when an extension of the protocol in the same image proves it (extension P where Element: ~Copyable), which only a primary associated type (protocol P<Element>) can.
  • @storageRestrictions(initializes: _x) init in an accessor block is inferred, not read (from 0.25.0). No binary records the attribute (SE-0400 init accessors): it is printed when the type has a stored property _x of the property's own type — what @Observable and most hand-written storage do — and it never lists accesses:. Otherwise a bare init prints under // init accessor: the binary does not record which stored properties it initializes. No init line does not mean no init accessor: the compiler gives one internal access unless it is @usableFromInline, so an optimized, dead-stripped image (most OS frameworks, shipped apps) keeps only the exported ones. dump lists each one it finds as X.x.init : T, with the inference on the line above.
  • Enum-layout patterns marked "not resolved offline" mean only the extra-inhabitant index is derivable statically; the concrete bytes need the live metadata.
  • An @objc protocol whose requirements carry @objc(selector), under the comment "Swift names follow the ClangImporter's rules for these selectors", is declared in Swift, but the binary keeps no Swift name for any requirement of an @objc protocol. When no class of the binary implements one, its Swift name is derived from the selector the way the importer would, so it can differ from the source (removeObject(at:) for remove(at:)); the selector, which is what the protocol means to the runtime, is exact. A requirement under // Taken from the conformer X. is X's own member and exact. __C.NSObject after such a protocol's colon is the NSObject protocol (Swift's NSObjectProtocol), spelled the way the compiler mangles it. dump --sections protocols on an image with no Swift protocols reports __swift5_protos not found and still lists these.
  • Objective-C protocols after a class's superclass (class X: __C.NSObject, M.P, __C.NSCopying) come from the class's Objective-C metadata: a conformance to an @objc protocol has no Swift conformance record. An extension in the class's own module is folded into the class there, so its conformances show in the header too, while extension __C.NSView: M.P {} is an extension of another module's class (its category). Neither shows in diff, evolution or a snapshot.
  • @objc(Name) above a class is the name the Objective-C runtime knows it by, and matters even when it equals the Swift name (@objc(NSScrollPocket) class NSScrollPocket): without it the runtime name would be the _TtC… mangling. That is also the class name objc headers and -[Class selector] comments use. @_objcRuntimeName(Name) is the same fact on a class with no Objective-C ancestor, where @objc would not be legal Swift (mostly the standard library) — not a typo.
  • A declaration under a comment like // Visitor #1 in Holder.countValues() is a type declared in a function or closure body. interface keeps it nested in the enclosing type and prints its bare name wherever it is referenced (nothing outside the body can spell it), so two methods' Visitors are two declarations that only the comment tells apart; their conformance extensions carry the compiler's full name (extension Visitor #1 in M.Holder.countValues() -> Any: P), and dump declares the type under that full name. (Visitor in $1a2b3c) is such a type in a binary stripped of every record of its function: the $ number is the address of the anonymous context descriptor that wraps it — the runtime's own spelling — not a private discriminator.

10. Where the details live

The repository is MachOSwiftSection.

NeedRead
Worked examples of every subcommand and flagits README.md, section "swift-section CLI Tool"
How to read an enum-layout commentDocumentations/SwiftEnumLayout.md (_zh companion)
Writing supplementary .apinotes for a private frameworkDocumentations/SupplementaryTypeMappings.md
The objc subcommands in full, including the snapshot / diff / evolution workflowDocumentations/ObjCCommandLine.md (_zh companion); the traps are in references/objc.md beside this file
refs and symbolicate: the line format, the routes, the trapsreferences/cross-references.md beside this file
What each flag does, authoritativelyswift-section <subcommand> --help (and swift-section objc <subcommand> --help) — generated from the code, so it cannot drift

Sponsors

Details

Marketplace
MxIris-Reverse-Engineering/MachOSwiftSection
Source
AgentPlugins/swift-section
Category
Community