Skip to content

[AUTOMATED] Name Objective-C selector and class reference slots and objc_msgSend$ stubs on arm64 Mach-O - #1476

Merged
mahaloz merged 11 commits into
Noelo-Lab:mainfrom
coleleavitt:apple/objc-selrefs
Nov 9, 2026
Merged

mahaloz merged 11 commits into
Noelo-Lab:mainfrom
coleleavitt:apple/objc-selrefs

Conversation

@coleleavitt

Copy link
Copy Markdown
Contributor

With --option objc on, a message send on arm64 Mach-O still reads its selector from an anonymous data slot, and the objc_msgSend$<sel> stubs that Xcode 14+ links route most sends through show up as sub_ calls.

kuna decompile decompiler/crates/kuna-analysis/tests/fixtures/macho_objc_refs_arm64 _use --option objc on

Before:

  v1 = objc_msgSend(a0,dat_1000081f8,2);
  return sub_1000008c0(a0) + v1;

After:

  v1 = objc_msgSend(a0,sel_greet_,2);
  return objc_msgSend$count(a0) + v1;
  • The objc pass names __objc_selrefs, __objc_classrefs and __objc_superrefs slots selRef_<sel>, classRef_<Class> and superRef_<Class> (a chained bind slot is named from its import), and each __objc_stubs entry objc_msgSend$<sel>. A stub gets a prototype when the image's own methods agree on the selector's type encoding; the x1 the stub loads itself is not an argument.
  • New option objcrefconst (default on, inert unless objc is on) reports the rebase ref slots constant, the way Ghidra's ObjC analyzer makes those sections read-only, so a load through selRef_x folds to sel_x and a classref receiver to _OBJC_CLASS_$_<Class>. Off keeps the named loads.
  • dynrelocs on a chained Mach-O now reports the rebase slots of SG_READ_ONLY segments (__DATA_CONST) constant, the Mach-O counterpart of PT_GNU_RELRO; __DATA slots are still written but not constant.
  • ChainedFixups gains is_chained() (true for a bind-only image too, so its packed bind words are never read as pointers), bind_name(va) and in_readonly_segment(va).

Tests: fixture macho_objc_refs_arm64 (source and link recipe in the fixtures README), fixture macho_bind_only_arm64, and stage test tests/stages/kuna-objcrefs.xml with three passes: objc off, objc on with objcrefconst off, objc on. The datatest corpus is unchanged (675/675).

… keep bind names

Upstream's dynrelocs Mach-O arm now writes every chained-fixup rebase into
the loaded image (Noelo-Lab#1358) but declares no slot constant. The slots of an
SG_READ_ONLY segment (__DATA_CONST, which dyld maps read-only once fixed up
-- the PT_GNU_RELRO of a Mach-O) are now reported constant through the same
dynreloc_const path; a __DATA slot is written but not declared constant.

The resolver also records the SG_READ_ONLY segments and answers bind_name
for a bind slot's import.

[AUTOMATED] Rebased onto upstream's chained-fixup resolver; the duplicate
rebase writer (loader/kuna_machorelocs.rs) is dropped.
…Send$ stubs

Code never touches a selector string or a class_t directly: a send loads its
selector from a __objc_selrefs slot, a class-method receiver from
__objc_classrefs, [super init] its class from __objc_superrefs, and a modern
link routes most sends through a __objc_stubs entry that loads the selref and
jumps to objc_msgSend. The objc pass left all four anonymous, so an iOS app
read objc_msgSendSuper2(&super, dat_1045b76f0) and sub_1034cd820(obj).

analyzers/objc/kuna_objcrefs.rs names each slot (selRef_<sel>,
classRef_<Class> / superRef_<Class>; a chained bind slot from its import) and
each stub objc_msgSend$<sel>, with the prototype of the image's own method for
that selector pinned past the x1 the stub owns, so a caller prints
objc_msgSend$greet:(obj, 5) rather than a dead x1. The rebase slots are
reported constant; the new option objcrefconst (on by default, inert unless
objc is on) paints them read-only and foldable the way dynrelocs treats RELRO
slots, so a send reads objc_msgSend(obj, sel_init) and a super call shows
_OBJC_CLASS_$_Derived -- what Ghidra's ObjectiveC2_ClassAnalyzer does by marking
the three ref blocks read-only. Bind slots keep their classRef_ name.

Stage test tests/stages/kuna-objcrefs.xml over the new macho_objc_refs_arm64
fixture (three passes: objc off, objc on + objcrefconst off, objc on); spec
prose in docs/spec/01-program-prep.md; catalog 339 -> 340 settables.

[AUTOMATED] Toyota.app, 499 sampled functions with --option objc on: 274
anonymous __objc_stubs calls -> 276 named objc_msgSend$<sel> calls (138
selectors), 10 of 10 direct objc_msgSend* selector arguments named, 61
classRef_ uses; 499-function run 30.8-34.0 s before vs 31.1-32.6 s after.
- objc: on a chained image the reference slots are reported constant only
  while dynrelocs is on -- off, the loader leaves the packed chain word in the
  slot and a fold would read it (gate test covers the Mach-O arm).
- tests/stages/README.md: the kuna-objcrefs row fits the 3-column table.

[AUTOMATED] Addresses the review on #1. The multi-start page
walk and the import-name cache this commit also carried are upstream's now
(Noelo-Lab#1358) and were dropped in the rebase.
ChainedFixups::is_empty() only counted rebases, so on a chained image whose
fixups are all binds MachoImage::chained() was false and rebase_ptr handed the
packed bind word back as a pointer (an imported class ref lost its name).
Record the presence of LC_DYLD_CHAINED_FIXUPS itself (is_chained) and key the
ObjC walk on that. New fixture macho_bind_only_arm64: one bind, no rebase.

[AUTOMATED] Addresses the CodeAnt comment on #1.
…baseline

[AUTOMATED] Regenerated after rebasing onto upstream/main.
@coleleavitt

Copy link
Copy Markdown
Contributor Author

[AUTOMATED] @mahaloz ready for review when you have time.

mahaloz and others added 6 commits November 7, 2026 19:38
Count/baseline conflicts only (xml.rs corpus count, kuna_phases/tests.rs, catalog_bytecompat.rs, kuna-catalog.xml, baseline-stages.json): counts re-derived, stage baseline merged as main + this PR's delta.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKS1xSN6UHyTiGivmGe
…bytes

section_slots enumerated 0..sec.size()/ps from the section header, so a
Mach-O whose __objc_selrefs header claims 0x0800000000000000 bytes made
the objc pass try to allocate 2^59 bytes and abort the whole decompile
("memory allocation of 576460752303423488 bytes failed"). The objc pass
runs on default flags for images under 500 KiB (auto -> aggressive turns
objc on), so a 50 KB crafted file was enough:

  kuna decompile selrefs_huge _use      # aborted; now decompiles

The walk now stops at the bytes the file actually backs the section
with (sec.data(), as the classlist walk already does) and rejects a
range that would wrap the address space. The stub scanners' pc
arithmetic wraps instead of overflowing on a section mapped at the top
of the address space.

The stage README row and the kuna-objcrefs.xml comment no longer name
the third-party app the measurement came from.

Tests: kuna_objcrefs::tests::oversized_ref_section_header_is_bounded_by_file_data,
kuna_objcrefs::tests::stub_scan_wraps_at_the_top_of_the_address_space
(both fail on the previous code: abort and overflow panic).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKS1xSN6UHyTiGivmGe
… objc's preset default

Objective-C string reads and record walks were bounded per list (4096 records)
but not per image: a crafted 340 KB image whose classlist entries all point at
one class with 4096 long-selector methods costs one selector copy per record and
ran past 8 GB (macho longstr case: 11.2 s to abort on the prior build, 0.29 s and
127 MB now). The same pattern reaches every list this series adds. MachoImage now
carries a work budget (eight times the mapped bytes, floor 16 MiB): each record
and each string byte spends from it and an exhausted budget ends the walk.

objc is off in the shipped catalog but on in the aggressive preset, which auto
selects below 500 KiB: say so in its option row, the objcrefconst row and the
spec. Membership is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKS1xSN6UHyTiGivmGe
…to into an arm dedupitetail unwraps (Noelo-Lab#1488)

Two more regression tests for a crash fixed by Noelo-Lab#1327: when the dedupitetail
pass hoists a statement both arms of an if/else end with, it frees a block a
goto may still name, and printing the goto's label panicked. These tests cover
two shapes that reach the freed block: a goto out of a loop and a switch-case
goto.

Each test is a hand-written x86-64 fixture decompiled twice: dedupitetail off,
then the default. The off pass prints shared() in both arms; the default pass
hoists it after the if and logs `// ite-dedupe`. Both passes must still print
the goto and the label on the arm's first statement.

Tests only, no code change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKS1xSN6UHyTiGivmGe
…ndstarts) (Noelo-Lab#1496)

A Mach-O whose LC_FUNCTION_STARTS was stripped loses nearly all its function
starts on arm64, because kuna has no prologue sweep there. With `--option
unwindstarts on`, kuna now reads function starts out of the
__TEXT,__unwind_info section the unwinder needs, which survives the strip. In
a real stripped 706 KB arm64 binary this recovers 417 more of its 1,695 real
functions (1,042 -> 1,459).

At load, every Mach-O's __unwind_info is parsed (first-level index, then
regular and compressed second-level pages) into absolute addresses, filtered
to executable sections and not already named by a symbol. The list is
committed as function entries only if the option is on. The compact encodings
are ignored; only the starts are used. The parser's work is bounded on
malformed sections.

unwindstarts is off by default and not in the aggressive preset: it only helps
images without LC_FUNCTION_STARTS and adds nothing when that command is
present (0 functions added on 30 slices that keep it). With the option off,
decompile-all is byte-identical on the repo's 32 Mach-O files and on 3 real
binaries (2,887 functions in total).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKS1xSN6UHyTiGivmGe
@mahaloz
mahaloz merged commit aa3b198 into Noelo-Lab:main Nov 9, 2026
2 checks passed
coleleavitt added a commit to coleleavitt/kuna that referenced this pull request Nov 9, 2026
…1521-Noelo-Lab#1523

upstream/main (82e29e9) carries the 18 Apple PRs (Noelo-Lab#1476-Noelo-Lab#1496) as squash
commits plus its own later edits; this merge takes upstream's version of that
code except where all carries a later fix on top.

Kept from all: outlined objc_retain_x<N> in x0, the argument-less static
metadata accessor, vtabletypes, treeswitch, callothernoreturn and the default
flips (importdata, itaniumeh, relronoreturn, condfold), the fix-objc selector
rule (two classes spelling one selector leave it naming neither), the 32-bit
CFString flags word, the fix-swift-loader fixes (folded-claim owners by
descriptor, Swift extension nested types, stale swiftself readers), and the
hostile-input bounds of the dyld cache, kernelcache and chained-fixup loaders
(those three modules stay all's, with its 32-bit cache, companion image and
prelinked-kernelcache support).

Taken from upstream: the arm64e ptrauthtrap return-address shape check, the
dyldinfo bind replay with its operation budget (all's addend plumbing kept),
encoding_for_class without the selector-wide fallback, the cfstrings walk
budget, the Swift demangler revisions, class-bound witness self, the arm64
x21 error test, the objc/swift metadata work budgets, and Noelo-Lab#1521's option
policy (CLAUDE.md now states it; docs/agents.md stays dropped).

Noelo-Lab#1522/Noelo-Lab#1523 made 66 options unconditional; their rows, dispatch arms and
ArchContext fields are dropped here too. phases.toml is upstream's registry
plus all's 94 remaining rows (427 settables: 93 core / 187 transform /
147 analysis, 197 live readers). Regenerated: docs/options.md,
phase_catalog.json, docs/baseline-stages.json (all 4614 stage assertions
pass; the removed keys belong to tests of dropped options), corpus count 841.
mahaloz pushed a commit that referenced this pull request Nov 13, 2026
…loader work (#1476-#1496) (#1527)

Follow-up fixes to the Objective-C, Swift and Mach-O loader work, none behind a new option:
- Objective-C: a struct encoding's pointer member is one field (`{S=^i}` is one `int *`). An SDK-header C function pointer is no longer read as a block `@?`; it claims its selector as unspellable. A selector two classes declare with different classes types its stub with neither, from the image's own metadata and from SDK headers. `read_cstr` scans no further than the walk budget.
- Mach-O: a `__cfstring` entry already under a data symbol still renders as `CFSTR("...")`. `__unwind_info` is read only from `__TEXT` and only at header version 1. The `unwindstarts` text now says one start per unwind entry. The `docs/options.md` symptom index links to the full GitHub heading anchors.
- Swift types: metadata is located from an accessor that ends its section, a type nested in an extension resolves through the extended type, and a class with a resilient superclass is not laid out statically. Metadata names no function at a misaligned arm64 address or strictly inside a sized symbol or single-function FDE body.
- Swift calls: a struct method keeps the `self` its caller set across an earlier call that does not read swiftself. That is a callee whose straight-line body never reads it (stores through the stack pointer don't count), or a module-level function by its symbol. A getter with a pinned `self` keeps `__swiftcall`. A swifterror register spilled to a stack slot and reloaded is still followed. An indirect call takes `__swiftcall` only when its slot is reached through a loaded pointer or swiftself is set for it; a C callback or import-stub jump keeps the C model.
- New fixtures: swift_call_{leaf,free,spill,hook}_elf and swift_ext_types_elf (sources and recipes in the fixtures README). New stage passes 7-9 are in kuna-swiftcall.xml.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants