Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

feat(native): decode Swift nominal type declarations from __swift5_types (#6257)

Kaoru0822c02945bc440c
diff --git a/docs/native-investigation.md b/docs/native-investigation.md
index a47dd3093..4e9f19c17 100644
--- a/docs/native-investigation.md
+++ b/docs/native-investigation.md
@@ -462,9 +462,9 @@ complete observation.
`rea inspect-native-dispatch-metadata <app-or-binary>` prefers a validated macOS Mach-O byte reader. It decodes
64-bit little-endian Objective-C class/metaclass records, superclass pointers,
absolute/relative method entries, ivar offsets/sizes/alignment and protocol
- declarations. It also decodes simple Swift conformances, static synchronous
- witness slots, signed-relative pointers and non-generic, non-resilient class
- vtable descriptors. Records include exact virtual addresses/file offsets and
+ declarations. It also decodes Swift nominal type declarations, simple Swift
+ conformances, static synchronous witness slots, signed-relative pointers and
+ non-generic, non-resilient class vtable descriptors. Records include exact virtual addresses/file offsets and
artifact evidence. Vtable indexes are metadata word offsets; witness indexes
start after the conformance header. Names unavailable in metadata remain null.
The byte reader holds the whole selected file in memory, so it admits files up
@@ -475,6 +475,20 @@ complete observation.
(`default` or `caller`) and the bytes retained. A refusal names the observed
file size, the effective budget and its source, and either the budget to
select or, above 1 GiB, a deep analysis provider.
+ `swift_decls` lists each `__swift5_types` nominal type descriptor, which
+ survives stripping: `kind` (`class`, `struct`, `enum`, or `actor` from the
+ class actor flag), the descriptor's own `name`, `module`, `qualified_name`
+ (`Outer.Inner`), `generic`, the metadata `accessor_address`, the descriptor
+ `location`, and evidence citing its `__swift5_types` record.
+ Private and local types set `anonymous_context` because their anonymous
+ context is omitted from `qualified_name`. When a parent context cannot be
+ resolved, such as an extension of a type named only by a mangled name, a
+ missing module, or a cyclic chain, `qualified_name` is null and the entry is
+ partial with a reason. Access level, superclass, conformances, and fields are
+ not reported by this facet. The `swift_declarations` coverage counters count
+ examined type records and fully decoded declarations. Class vtable recovery
+ reads the same descriptors, so an unreadable type record also keeps
+ `swift_class_vtable_descriptors` partial.
The `swift_class_vtable_descriptors` coverage counters count examined vtable
slots and successfully decoded slots, rather than type-section entries.
The `objc_class_method_ivar_metadata` counters count admitted class and
diff --git a/scripts/verify/apple/dispatch.mjs b/scripts/verify/apple/dispatch.mjs
index 316437266..14a34b2a6 100644
--- a/scripts/verify/apple/dispatch.mjs
+++ b/scripts/verify/apple/dispatch.mjs
@@ -195,6 +195,72 @@ const checkSwift = (metadata, mode) => {
);
};
+/** Declarations from dispatch.swift that survive stripping unchanged. */
+const EXPECTED_SWIFT_DECLS = [
+ ["struct", "ReaWitnessFixture", false],
+ ["class", "ReaVtableFixture", false],
+ ["enum", "ReaDeclFixtureEnum", false],
+ ["struct", "ReaDeclFixtureOuter", false],
+ ["struct", "ReaDeclFixtureOuter.Inner", false],
+ ["struct", "ReaDeclFixtureGeneric", true],
+ ["actor", "ReaDeclFixtureActor", false],
+];
+
+/** Stable declaration facts compared across the symbols and stripped builds. */
+const swiftDeclarations = (metadata) =>
+ metadata.swift_decls.map((item) => ({
+ kind: item.kind,
+ qualified_name: item.qualified_name,
+ module: item.module,
+ generic: item.generic,
+ descriptor: item.location.address,
+ accessor: item.accessor_address,
+ status: item.decode.status,
+ }));
+
+const checkSwiftDeclarations = (metadata, mode) => {
+ const declarations = swiftDeclarations(metadata);
+ for (const [kind, qualifiedName, generic] of EXPECTED_SWIFT_DECLS)
+ assert.ok(
+ declarations.some(
+ (item) =>
+ item.kind === kind &&
+ item.qualified_name === qualifiedName &&
+ item.module === "ReaWitnessFixture" &&
+ item.generic === generic &&
+ item.accessor !== null &&
+ item.status === "decoded",
+ ),
+ `Swift declaration ${qualifiedName} missing (${mode.mode}): ${JSON.stringify(declarations)}`,
+ );
+ assert.equal(
+ metadata.coverage.find(({ facet }) => facet === "swift_declarations")
+ ?.status,
+ "complete",
+ );
+ return declarations;
+};
+
+/** Descriptor and accessor addresses must be the compiler's Mn/Ma symbols. */
+const checkSwiftSymbolAddresses = async (path, declarations) => {
+ const { stdout } = await exec("/usr/bin/nm", ["--defined-only", path]);
+ const symbols = (suffix) =>
+ new Set(
+ stdout.split("\n").flatMap((line) => {
+ const [address, , name] = line.trim().split(/\s+/u);
+ return name?.endsWith(suffix) === true
+ ? [`0x${BigInt(`0x${address}`).toString(16)}`]
+ : [];
+ }),
+ );
+ const descriptors = symbols("Mn");
+ const accessors = symbols("Ma");
+ for (const item of declarations) {
+ assert.ok(descriptors.has(item.descriptor), JSON.stringify(item));
+ assert.ok(accessors.has(item.accessor), JSON.stringify(item));
+ }
+};
+
const root = await mkdtemp(join(tmpdir(), "rea-dispatch-"));
let report;
try {
@@ -259,14 +325,21 @@ try {
"-o",
swiftPath,
]);
+ let unstrippedDeclarations;
for (const variant of ["symbols", "stripped"]) {
if (variant === "stripped")
await exec("/usr/bin/strip", ["-x", swiftPath]);
const { target, metadata } = await inspect(swiftPath);
checkSwift(metadata, mode);
+ const declarations = checkSwiftDeclarations(metadata, mode);
+ if (variant === "symbols") {
+ await checkSwiftSymbolAddresses(swiftPath, declarations);
+ unstrippedDeclarations = declarations;
+ } else assert.deepEqual(declarations, unstrippedDeclarations);
results.push({
variant: `swift-${mode.mode}-${variant}`,
target_sha256: target.sha256,
+ declarations: declarations.length,
conformances: metadata.swift_conformances.length,
slots: metadata.swift_dispatch_slots.length,
fixups: fixupCoverage(metadata)?.reason,
diff --git a/src/domain/native/objcSwiftMetadata.ts b/src/domain/native/objcSwiftMetadata.ts
index b619ae6ec..b056c894a 100644
--- a/src/domain/native/objcSwiftMetadata.ts
+++ b/src/domain/native/objcSwiftMetadata.ts
@@ -290,38 +290,26 @@ export type ObjcClassImportBindingCoverage = z.infer<
typeof objcClassImportBindingCoverageSchema
>;
-/** Swift declaration kind. */
-export const swiftDeclKindSchema = z.enum([
- "class",
- "struct",
- "enum",
- "protocol",
- "extension",
- "actor",
- "global_var",
- "global_func",
-]);
+/** Nominal Swift type kinds recorded by `__swift5_types` descriptors. */
+export const swiftDeclKindSchema = z.enum(["class", "struct", "enum", "actor"]);
-/** Swift access level. */
-export const swiftAccessLevelSchema = z.enum([
- "private",
- "fileprivate",
- "internal",
- "public",
- "open",
-]);
-/** Swift declaration metadata. */
+/**
+ * One nominal type context descriptor. `location` is the descriptor itself;
+ * evidence cites its `__swift5_types` record. `qualified_name` is null when a
+ * parent context is unresolved, rather than a shortened guess.
+ */
export const swiftDeclSchema = z.strictObject({
kind: swiftDeclKindSchema,
name: z.string().min(1),
- module: z.string().nullable(),
- access_level: swiftAccessLevelSchema.default("internal"),
- super_class: z.string().nullable(),
- protocols: z.array(z.string()).default([]),
- is_final: z.boolean().default(false),
- is_required: z.boolean().default(false),
- is_convenience_init: z.boolean().default(false),
- is_override: z.boolean().default(false),
+ qualified_name: z.string().min(1).nullable(),
+ module: z.string().min(1).nullable(),
+ generic: z.boolean(),
+ /** A private or local declaration context was omitted from `qualified_name`. */
+ anonymous_context: z.boolean(),
+ accessor_address: z.string().min(1).nullable(),
+ location: nativeMetadataLocationSchema,
+ decode: nativeMetadataDecodeSchema,
+ evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
/** Database save/read operation type. */
diff --git a/src/native/AppleDispatchCoverage.ts b/src/native/AppleDispatchCoverage.ts
index 3d5ef4afd..437eab82c 100644
--- a/src/native/AppleDispatchCoverage.ts
+++ b/src/native/AppleDispatchCoverage.ts
@@ -33,6 +33,7 @@ export const pushDispatchCoverage = (input: {
readonly objcListScanTruncated: boolean;
readonly objcClassListScanTruncated: boolean;
readonly fixups: PointerFixups;
+ readonly declarations: FacetDecodeFacts;
readonly vtables: FacetDecodeFacts;
readonly swift: FacetDecodeFacts;
}): void => {
@@ -46,6 +47,7 @@ export const pushDispatchCoverage = (input: {
objcListScanTruncated,
objcClassListScanTruncated,
fixups,
+ declarations,
vtables,
swift,
} = input;
@@ -177,7 +179,7 @@ export const pushDispatchCoverage = (input: {
facet: "swift_generic_resilient_witnesses_overrides_async_coroutines",
status: "unsupported",
reason:
- "This reader admits simple Swift conformance/static witness records and non-generic, non-resilient class vtables; generic/resilient tables and other Swift metadata families are not decoded",
+ "This reader admits Swift nominal type declarations, simple conformance/static witness records and non-generic, non-resilient class vtables; generic/resilient tables and other Swift metadata families are not decoded",
examined: 0,
decoded: 0,
});
@@ -212,6 +214,17 @@ export const pushDispatchCoverage = (input: {
examined: swift.examined,
decoded: swift.decoded,
});
+ result.coverage.push({
+ facet: "swift_declarations",
+ status: declarations.exhaustive && !truncated ? "complete" : "partial",
+ reason:
+ [
+ ...declarations.issues.map(formatIssue),
+ ...(truncated ? ["max_records_reached"] : []),
+ ].join("; ") || null,
+ examined: declarations.examined,
+ decoded: declarations.decoded,
+ });
result.coverage.push({
facet: "swift_class_vtable_descriptors",
status:
diff --git a/src/native/AppleDispatchDecodeFacts.ts b/src/native/AppleDispatchDecodeFacts.ts
index 699235d16..3105dfc83 100644
--- a/src/native/AppleDispatchDecodeFacts.ts
+++ b/src/native/AppleDispatchDecodeFacts.ts
@@ -5,6 +5,7 @@ export type DispatchFacet =
| "objc_properties_categories"
| "pointer_fixups"
| "swift_conformances_static_witness_slots"
+ | "swift_declarations"
| "swift_class_vtable_descriptors";
export interface DecodeIssue {
diff --git a/src/native/AppleDispatchMetadata.test.ts b/src/native/AppleDispatchMetadata.test.ts
index f88b10cf1..efbd58e4c 100644
--- a/src/native/AppleDispatchMetadata.test.ts
+++ b/src/native/AppleDispatchMetadata.test.ts
@@ -1569,6 +1569,10 @@ describe("malformed Apple dispatch metadata", () => {
"EarlierClass",
"LaterClass",
]);
+ expect(result.swift_decls.map(({ name }) => name)).toEqual([
+ "EarlierClass",
+ "LaterClass",
+ ]);
const coverage = result.coverage.find(
({ facet }) => facet === "swift_class_vtable_descriptors",
);
@@ -1576,7 +1580,7 @@ describe("malformed Apple dispatch metadata", () => {
status: "partial",
examined: 2,
decoded: 2,
- reason: expect.stringContaining("class name is empty"),
+ reason: expect.stringContaining("type descriptor name is empty"),
});
});
diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts
index b99f78672..d0f3f4d80 100644
--- a/src/native/AppleDispatchMetadata.ts
+++ b/src/native/AppleDispatchMetadata.ts
@@ -48,7 +48,8 @@ import {
type DispatchRecordBudget,
type SwiftRelativeTargetLocation,
} from "./AppleSwiftDispatchFacets.js";
-import { decodeSwiftClassVtables } from "./AppleSwiftVtables.js";
+import { createSwiftClassVtableDecoder } from "./AppleSwiftVtables.js";
+import { decodeSwiftNominalTypes } from "./AppleSwiftNominalTypes.js";
import { inspectObjcClassImportBindings } from "./AppleObjcClassImportBindings.js";
/** Decode validated little-endian 64-bit Apple Objective-C metadata without loading target code. */
@@ -221,23 +222,37 @@ export const decodeAppleDispatchMetadata = (
typeEntries.push(section.address + BigInt(index * 4));
if (section.size / 4 > maxRecords) budget.truncated = true;
}
- const vtables = decodeSwiftClassVtables({
+ const admit = () => budget.admit();
+ const executable = (address: bigint) =>
+ segments.some(
+ (segment) =>
+ segment.executable &&
+ address >= segment.address &&
+ address < segment.address + segment.size,
+ );
+ const vtables = createSwiftClassVtableDecoder({
+ result,
+ readers: {
+ u32,
+ relative: swiftRelative,
+ location,
+ evidence,
+ admit,
+ executable,
+ },
+ });
+ const declarations = decodeSwiftNominalTypes({
entries: typeEntries,
result,
+ visitor: vtables.visitor,
readers: {
u32,
relative: swiftRelative,
string,
location,
evidence,
- admit: () => budget.admit(),
- executable: (address) =>
- segments.some(
- (segment) =>
- segment.executable &&
- address >= segment.address &&
- address < segment.address + segment.size,
- ),
+ executable,
+ admit,
},
});
pushDispatchCoverage({
@@ -250,7 +265,8 @@ export const decodeAppleDispatchMetadata = (
objcClassListScanTruncated,
truncated: budget.truncated,
fixups,
- vtables,
+ declarations,
+ vtables: vtables.facts(),
swift,
});
return objcSwiftMetadataSchema.parse(result);
diff --git a/src/native/AppleObjcProtocols.ts b/src/native/AppleObjcProtocols.ts
index 13bc76f8d..70de17c2a 100644
--- a/src/native/AppleObjcProtocols.ts
+++ b/src/native/AppleObjcProtocols.ts
@@ -1,10 +1,10 @@
import type { ObjcSwiftMetadata } from "../domain/native/objcSwiftMetadata.js";
-import type { SwiftMetadataReaders } from "./AppleSwiftVtables.js";
+import type { SwiftNominalReaders } from "./AppleSwiftNominalTypes.js";
/** Read protocol lists and absolute protocol method declarations with cycle-safe identities. */
export const createObjcProtocolReader = (input: {
readers: Pick<
- SwiftMetadataReaders,
+ SwiftNominalReaders,
"u32" | "string" | "location" | "evidence" | "admit"
> & {
pointer(address: bigint): bigint;
diff --git a/src/native/AppleSwiftDispatchFacets.ts b/src/native/AppleSwiftDispatchFacets.ts
index 433d748ec..0d5950d7c 100644
--- a/src/native/AppleSwiftDispatchFacets.ts
+++ b/src/native/AppleSwiftDispatchFacets.ts
@@ -47,7 +47,9 @@ export type SwiftRelativeField =
| "typeName"
| "witnessTablePattern"
| "typeMetadataRecord"
- | "classDescriptorName"
+ | "contextParent"
+ | "moduleName"
+ | "typeAccessFunction"
| "methodImplementation";
type SwiftRelativeFieldContract = {
@@ -67,7 +69,9 @@ const relativeFieldContracts = {
typeName: { encoding: "direct", nullability: "nonnull" },
witnessTablePattern: { encoding: "direct", nullability: "nullable" },
typeMetadataRecord: { encoding: "taggedDirect", nullability: "nonnull" },
- classDescriptorName: { encoding: "direct", nullability: "nonnull" },
+ contextParent: { encoding: "indirectable", nullability: "nullable" },
+ moduleName: { encoding: "direct", nullability: "nonnull" },
+ typeAccessFunction: { encoding: "direct", nullability: "nullable" },
methodImplementation: {
encoding: "compactFunction",
nullability: "nullable",
diff --git a/src/native/AppleSwiftNominalTypes.test.ts b/src/native/AppleSwiftNominalTypes.test.ts
new file mode 100644
index 000000000..3d300f7da
--- /dev/null
+++ b/src/native/AppleSwiftNominalTypes.test.ts
@@ -0,0 +1,482 @@
+import { describe, expect, it } from "vitest";
+import { decodeAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
+
+const provenance = { path: "/fixture/app", sha256: "a".repeat(64) };
+const BASE = 0x100000000n;
+const TYPES = 0x200;
+
+/** One-segment arm64 image whose `__swift5_types` lists `descriptors`. */
+const nominalImage = (
+ build: (image: {
+ u32(at: number, value: number): void;
+ rel(at: number, target: number): void;
+ text(at: number, value: string): void;
+ }) => readonly number[],
+ size = 4096,
+) => {
+ const bytes = Buffer.alloc(size);
+ const u32 = (at: number, value: number) => bytes.writeUInt32LE(value, at);
+ const rel = (at: number, target: number) =>
+ bytes.writeInt32LE(target - at, at);
+ const text = (at: number, value: string) => bytes.write(`${value}\0`, at);
+ const descriptors = build({ u32, rel, text });
+ u32(0, 0xfeedfacf);
+ u32(4, 0x0100000c);
+ u32(12, 2);
+ u32(16, 1);
+ u32(20, 152);
+ u32(32, 0x19);
+ u32(36, 152);
+ bytes.write("__TEXT", 40);
+ bytes.writeBigUInt64LE(BASE, 56);
+ bytes.writeBigUInt64LE(BigInt(size), 64);
+ bytes.writeBigUInt64LE(BigInt(size), 80);
+ u32(88, 5);
+ u32(92, 5);
+ u32(96, 1);
+ bytes.write("__swift5_types", 104);
+ bytes.write("__TEXT", 120);
+ bytes.writeBigUInt64LE(BASE + BigInt(TYPES), 136);
+ bytes.writeBigUInt64LE(BigInt(descriptors.length * 4), 144);
+ u32(152, TYPES);
+ descriptors.forEach((descriptor, index) =>
+ rel(TYPES + index * 4, descriptor),
+ );
+ return bytes;
+};
+
+const MODULE = 0x300;
+
+/** Context descriptor: flags, parent, name and optional accessor. */
+const context = (
+ image: Parameters<Parameters<typeof nominalImage>[0]>[0],
+ at: number,
+ flags: number,
+ parent: number | null,
+ name?: { at: number; value: string },
+ accessor?: number,
+) => {
+ image.u32(at, flags);
+ if (parent !== null) image.rel(at + 4, parent);
+ if (name !== undefined) {
+ image.text(name.at, name.value);
+ image.rel(at + 8, name.at);
+ }
+ if (accessor !== undefined) image.rel(at + 12, accessor);
+};
+
+const declarationsImage = () =>
+ nominalImage((image) => {
+ context(image, MODULE, 0, null, { at: 0x700, value: "ReaMod" });
+ context(image, 0x320, 0x51, MODULE, { at: 0x710, value: "Outer" }, 0x900);
+ context(image, 0x340, 0x52, 0x320, { at: 0x720, value: "Inner" }, 0x910);
+ // Class with the IsActor kind-specific flag and no vtable.
+ context(
+ image,
+ 0x360,
+ 0x00800050,
+ MODULE,
+ { at: 0x730, value: "Act" },
+ 0x920,
+ );
+ // Generic struct with a null (ABI-nullable) accessor.
+ context(image, 0x380, 0xd1, MODULE, { at: 0x740, value: "Box" });
+ // Private class inside an anonymous context.
+ context(image, 0x3c0, 0x42, MODULE);
+ context(image, 0x3a0, 0x50, 0x3c0, { at: 0x750, value: "Hidden" }, 0x930);
+ // Struct declared in an extension of a type named by a mangled name.
+ context(image, 0x400, 0x41, MODULE, { at: 0x760, value: "Si" });
+ context(
+ image,
+ 0x3e0,
+ 0x51,
+ 0x400,
+ { at: 0x770, value: "ExtNested" },
+ 0x940,
+ );
+ // Struct without a parent module.
+ context(image, 0x420, 0x51, null, { at: 0x780, value: "Orphan" }, 0x950);
+ // Protocol descriptor listed as a type.
+ context(image, 0x440, 0x03, MODULE, { at: 0x790, value: "Proto" });
+ // Two structs that name each other as parents.
+ context(image, 0x460, 0x51, 0x480, { at: 0x7a0, value: "LoopA" }, 0x960);
+ context(image, 0x480, 0x51, 0x460, { at: 0x7b0, value: "LoopB" }, 0x970);
+ return [0x320, 0x340, 0x360, 0x380, 0x3a0, 0x3e0, 0x420, 0x440, 0x460];
+ });
+
+const hex = (offset: number) => `0x${(BASE + BigInt(offset)).toString(16)}`;
+
+/** Projection of `declarationsImage` declarations in record order. */
+const EXPECTED_DECLARATIONS = [
+ {
+ kind: "struct",
+ name: "Outer",
+ qualified_name: "Outer",
+ module: "ReaMod",
+ generic: false,
+ anonymous_context: false,
+ accessor_address: hex(0x900),
+ status: "decoded",
+ },
+ {
+ kind: "enum",
+ name: "Inner",
+ qualified_name: "Outer.Inner",
+ module: "ReaMod",
+ generic: false,
+ anonymous_context: false,
+ accessor_address: hex(0x910),
+ status: "decoded",
+ },
+ {
+ kind: "actor",
+ name: "Act",
+ qualified_name: "Act",
+ module: "ReaMod",
+ generic: false,
+ anonymous_context: false,
+ accessor_address: hex(0x920),
+ status: "decoded",
+ },
+ {
+ kind: "struct",
+ name: "Box",
+ qualified_name: "Box",
+ module: "ReaMod",
+ generic: true,
+ anonymous_context: false,
+ accessor_address: null,
+ status: "decoded",
+ },
+ {
+ kind: "class",
+ name: "Hidden",
+ qualified_name: "Hidden",
+ module: "ReaMod",
+ generic: false,
+ anonymous_context: true,
+ accessor_address: hex(0x930),
+ status: "decoded",
+ },
+ {
+ kind: "struct",
+ name: "ExtNested",
+ qualified_name: null,
+ module: "ReaMod",
+ generic: false,
+ anonymous_context: false,
+ accessor_address: hex(0x940),
+ status: "partial",
+ },
+ {
+ kind: "struct",
+ name: "Orphan",
+ qualified_name: null,
+ module: null,
+ generic: false,
+ anonymous_context: false,
+ accessor_address: hex(0x950),
+ status: "partial",
+ },
+ {
+ kind: "struct",
+ name: "LoopA",
+ qualified_name: null,
+ module: null,
+ generic: false,
+ anonymous_context: false,
+ accessor_address: hex(0x960),
+ status: "partial",
+ },
+];
+
+describe("Swift nominal type declarations", () => {
+ it("decodes kind, qualified name, module and accessor from descriptors", () => {
+ const result = decodeAppleDispatchMetadata(
+ declarationsImage(),
+ 1000,
+ provenance,
+ );
+
+ expect(
+ result.swift_decls.map((declaration) => ({
+ kind: declaration.kind,
+ name: declaration.name,
+ qualified_name: declaration.qualified_name,
+ module: declaration.module,
+ generic: declaration.generic,
+ anonymous_context: declaration.anonymous_context,
+ accessor_address: declaration.accessor_address,
+ status: declaration.decode.status,
+ })),
+ ).toEqual(EXPECTED_DECLARATIONS);
+ expect(result.swift_decls[5]?.decode.reason).toContain(
+ "extended type is not demangled",
+ );
+ expect(result.swift_decls[6]?.decode.reason).toContain("no parent module");
+ expect(result.swift_decls[7]?.decode.reason).toContain("cyclic");
+ expect(result.swift_decls[1]).toMatchObject({
+ location: { address: hex(0x340), file_offset: 0x340 },
+ evidence: [
+ { location: { address: hex(TYPES + 4), file_offset: TYPES + 4 } },
+ ],
+ });
+ expect(
+ result.coverage.find(({ facet }) => facet === "swift_declarations"),
+ ).toMatchObject({
+ status: "partial",
+ examined: 9,
+ decoded: 5,
+ reason: expect.stringContaining(
+ `unsupported_type_descriptor_kind at ${hex(TYPES + 28)}`,
+ ),
+ });
+ // Neither class declares a vtable, so the vtable facet stays complete.
+ expect(
+ result.coverage.find(
+ ({ facet }) => facet === "swift_class_vtable_descriptors",
+ ),
+ ).toMatchObject({ status: "complete", examined: 0 });
+ });
+
+ it("reads each shared parent context once", () => {
+ const result = decodeAppleDispatchMetadata(
+ declarationsImage(),
+ 1000,
+ provenance,
+ );
+ const reads = (field: number) =>
+ result.relative_pointers.filter(
+ (pointer) => pointer.field.address === hex(field),
+ ).length;
+
+ // Module name, Outer's name and Outer's parent are each shared.
+ expect(reads(MODULE + 8)).toBe(1);
+ expect(reads(0x320 + 8)).toBe(1);
+ expect(reads(0x320 + 4)).toBe(1);
+ });
+
+ it("retains the decoded prefix and reports the record budget", () => {
+ const result = decodeAppleDispatchMetadata(
+ declarationsImage(),
+ 12,
+ provenance,
+ );
+
+ expect(result.swift_decls.length).toBeGreaterThan(0);
+ expect(result.swift_decls.length).toBeLessThan(8);
+ expect(
+ result.coverage.find(({ facet }) => facet === "swift_declarations"),
+ ).toMatchObject({
+ status: "partial",
+ reason: expect.stringContaining("max_records_reached"),
+ });
+ });
+
+ it("follows an indirect parent pointer through its pointer slot", () => {
+ const bytes = nominalImage((image) => {
+ context(image, MODULE, 0, null, { at: 0x700, value: "ReaMod" });
+ context(image, 0x320, 0x51, null, { at: 0x710, value: "Viaslot" }, 0x900);
+ // Indirectable parent: odd displacement to a slot holding the module.
+ image.rel(0x324, 0x601);
+ return [0x320];
+ });
+ bytes.writeBigUInt64LE(BASE + BigInt(MODULE), 0x600);
+ const result = decodeAppleDispatchMetadata(bytes, 1000, provenance);
+
+ expect(result.swift_decls).toMatchObject([
+ {
+ qualified_name: "Viaslot",
+ module: "ReaMod",
+ decode: { status: "decoded" },
+ },
+ ]);
+ expect(
+ result.relative_pointers.find(
+ (pointer) => pointer.field.address === hex(0x324),
+ ),
+ ).toMatchObject({ indirect: true, target: { address: hex(MODULE) } });
+ });
+
+ it("keeps vtable coverage partial when a type record cannot be read", () => {
+ const bytes = nominalImage(() => [0x320]);
+ // Point the only record outside the image.
+ bytes.writeInt32LE(0x10000, TYPES);
+ const result = decodeAppleDispatchMetadata(bytes, 1000, provenance);
+
+ expect(result.swift_decls).toEqual([]);
+ for (const facet of [
+ "swift_declarations",
+ "swift_class_vtable_descriptors",
+ ])
+ expect(
+ result.coverage.find((coverage) => coverage.facet === facet),
+ ).toMatchObject({
+ status: "partial",
+ reason: expect.stringContaining(hex(TYPES)),
+ });
+ });
+});
+
+/** `count` structs, each nested in the previous one, in the given record order. */
+const nestedChainImage = (
+ count: number,
+ order: "parent-first" | "child-first",
+) =>
+ nominalImage((image) => {
+ context(image, MODULE, 0, null, { at: 0x700, value: "ReaMod" });
+ const descriptors = Array.from({ length: count }, (_, index) => {
+ const at = 0xa00 + index * 16;
+ context(
+ image,
+ at,
+ 0x51,
+ index === 0 ? MODULE : at - 16,
+ { at: 0xd00 + index * 4, value: `N${index}` },
+ 0x900,
+ );
+ return at;
+ });
+ return order === "parent-first" ? descriptors : descriptors.reverse();
+ });
+
+describe("Swift nominal type declaration bounds", () => {
+ it("bounds nesting depth independently of record order", () => {
+ const project = (order: "parent-first" | "child-first") =>
+ decodeAppleDispatchMetadata(
+ nestedChainImage(40, order),
+ 10_000,
+ provenance,
+ )
+ .swift_decls.map(({ name, qualified_name, decode }) => ({
+ name,
+ qualified_name,
+ status: decode.status,
+ }))
+ .sort(
+ (left, right) =>
+ Number(left.name.slice(1)) - Number(right.name.slice(1)),
+ );
+ const parentFirst = project("parent-first");
+
+ expect(project("child-first")).toEqual(parentFirst);
+ // The module and 31 nested types fill the 32-context bound.
+ expect(parentFirst[30]).toMatchObject({
+ status: "decoded",
+ qualified_name: Array.from(
+ { length: 31 },
+ (_, index) => `N${index}`,
+ ).join("."),
+ });
+ expect(parentFirst.slice(31).map(({ status }) => status)).toEqual(
+ Array.from({ length: 9 }, () => "partial"),
+ );
+ });
+
+ it("bounds the qualified name length", () => {
+ const result = decodeAppleDispatchMetadata(
+ nominalImage((image) => {
+ context(image, MODULE, 0, null, { at: 0x700, value: "ReaMod" });
+ context(image, 0x320, 0x51, MODULE, {
+ at: 0x1000,
+ value: "O".repeat(3000),
+ });
+ context(image, 0x340, 0x51, 0x320, {
+ at: 0x2000,
+ value: "I".repeat(2000),
+ });
+ return [0x320, 0x340];
+ }, 0x3000),
+ 1000,
+ provenance,
+ );
+
+ expect(result.swift_decls[0]?.qualified_name).toBe("O".repeat(3000));
+ expect(result.swift_decls[1]).toMatchObject({
+ qualified_name: null,
+ decode: {
+ status: "partial",
+ reason: expect.stringContaining("exceeds 4096 characters"),
+ },
+ });
+ });
+
+ it("decodes a class vtable before later declarations spend the budget", () => {
+ const result = decodeAppleDispatchMetadata(
+ nominalImage((image) => {
+ context(image, MODULE, 0, null, { at: 0x700, value: "ReaMod" });
+ // Class with a one-slot vtable at descriptor + 44.
+ context(image, 0x320, 0x80000050, MODULE, { at: 0x710, value: "C" });
+ image.u32(0x320 + 28, 1);
+ image.u32(0x320 + 48, 1);
+ image.rel(0x320 + 56, 0x900);
+ const structs = Array.from({ length: 50 }, (_, index) => {
+ const at = 0xa00 + index * 16;
+ context(image, at, 0x51, MODULE, {
+ at: 0xd00 + index * 4,
+ value: `S${index}`,
+ });
+ return at;
+ });
+ return [0x320, ...structs];
+ }),
+ 30,
+ provenance,
+ );
+
+ expect(result.swift_dispatch_slots).toMatchObject([
+ { owner: "C", decode: { status: "decoded" } },
+ ]);
+ expect(result.swift_decls.length).toBeLessThan(51);
+ expect(
+ result.coverage.find(({ facet }) => facet === "swift_declarations"),
+ ).toMatchObject({ status: "partial" });
+ });
+
+ it("keeps a non-executable accessor out of decoded declarations", () => {
+ const result = decodeAppleDispatchMetadata(
+ nominalImage((image) => {
+ context(image, MODULE, 0, null, { at: 0x700, value: "ReaMod" });
+ context(image, 0x320, 0x51, MODULE, { at: 0x710, value: "S" }, 0x5000);
+ return [0x320];
+ }),
+ 1000,
+ provenance,
+ );
+
+ expect(result.swift_decls).toMatchObject([
+ {
+ qualified_name: "S",
+ accessor_address: null,
+ decode: {
+ status: "partial",
+ reason: expect.stringContaining("not in executable mapped code"),
+ },
+ },
+ ]);
+ });
+
+ it("does not let a non-class name failure mark vtable coverage partial", () => {
+ const result = decodeAppleDispatchMetadata(
+ nominalImage((image) => {
+ context(image, MODULE, 0, null, { at: 0x700, value: "ReaMod" });
+ context(image, 0x320, 0x51, MODULE, { at: 0x710, value: "" });
+ return [0x320];
+ }),
+ 1000,
+ provenance,
+ );
+
+ expect(
+ result.coverage.find(({ facet }) => facet === "swift_declarations"),
+ ).toMatchObject({
+ status: "partial",
+ reason: expect.stringContaining("name is empty"),
+ });
+ expect(
+ result.coverage.find(
+ ({ facet }) => facet === "swift_class_vtable_descriptors",
+ ),
+ ).toMatchObject({ status: "complete" });
+ });
+});
diff --git a/src/native/AppleSwiftNominalTypes.ts b/src/native/AppleSwiftNominalTypes.ts
new file mode 100644
index 000000000..1bb2c74c6
--- /dev/null
+++ b/src/native/AppleSwiftNominalTypes.ts
@@ -0,0 +1,342 @@
+import type {
+ NativeMetadataEvidence,
+ NativeMetadataLocation,
+ ObjcSwiftMetadata,
+} from "../domain/native/objcSwiftMetadata.js";
+import { issue, type FacetDecodeFacts } from "./AppleDispatchDecodeFacts.js";
+import {
+ unresolvedSwiftRelativeReason,
+ type SwiftRelativeField,
+ type SwiftRelativeValue,
+} from "./AppleSwiftDispatchFacets.js";
+import { expectedSwiftMetadataReadFailure } from "./AppleSwiftMetadataReadFailure.js";
+
+/** Byte readers shared with the validated Mach-O metadata boundary. */
+export interface SwiftNominalReaders {
+ u32(address: bigint): number;
+ relative(address: bigint, kind: SwiftRelativeField): SwiftRelativeValue;
+ string(address: bigint): string;
+ location(address: bigint): NativeMetadataLocation;
+ evidence(address: bigint, description: string): NativeMetadataEvidence[];
+ executable(address: bigint): boolean;
+ admit(): boolean;
+}
+
+/** A `__swift5_types` descriptor whose kind and own name were read. */
+export interface SwiftNominalDescriptor {
+ readonly record: bigint;
+ readonly descriptor: bigint;
+ readonly flags: number;
+ readonly name: string;
+}
+
+/** A `__swift5_types` record that may be a class whose name is unknown. */
+export interface SwiftNominalRecordFailure {
+ readonly record: bigint;
+ readonly message: string;
+}
+
+/**
+ * Receives each descriptor as soon as its kind and name are read, so a
+ * consumer spends the record budget in record order rather than after every
+ * declaration.
+ */
+export interface SwiftNominalVisitor {
+ descriptor(descriptor: SwiftNominalDescriptor): void;
+ failure(failure: SwiftNominalRecordFailure): void;
+}
+
+const FACET = "swift_declarations";
+const CLASS = 16;
+const STRUCT = 17;
+const ENUM = 18;
+const MODULE = 0;
+const EXTENSION = 1;
+const ANONYMOUS = 2;
+const GENERIC = 0x80;
+const CLASS_IS_ACTOR = 0x80;
+/** Swift nesting is shallow; a longer chain is malformed or cyclic. */
+const MAXIMUM_CONTEXT_DEPTH = 32;
+/** Same bound as one metadata name, so nesting cannot multiply name storage. */
+const MAXIMUM_QUALIFIED_NAME_LENGTH = 4096;
+
+const hex = (value: bigint) => `0x${value.toString(16)}`;
+
+/**
+ * Facts of one context. `depth` counts contexts up to and including its
+ * module, so a cached result is valid wherever a walk reaches it.
+ */
+interface ContextFacts {
+ readonly module: string | null;
+ /** Dotted named path below the module; null when unresolved. */
+ readonly path: string | null;
+ readonly depth: number;
+ readonly anonymous: boolean;
+ readonly reason: string | null;
+ /** The walk stopped at its own bound; the result depends on its start. */
+ readonly walkLimited: boolean;
+}
+
+const unresolved = (reason: string, walkLimited = false): ContextFacts => ({
+ module: null,
+ path: null,
+ depth: 0,
+ anonymous: false,
+ reason,
+ walkLimited,
+});
+
+const tooDeep = (): ContextFacts =>
+ unresolved(
+ `Swift context parent chain exceeds ${MAXIMUM_CONTEXT_DEPTH} contexts or is cyclic`,
+ );
+
+/**
+ * Decode `__swift5_types` nominal type descriptors into `swift_decls`.
+ * Each context is read once, so shared parents add one relative-pointer
+ * record regardless of how many types they contain.
+ */
+export const decodeSwiftNominalTypes = (input: {
+ readers: SwiftNominalReaders;
+ entries: readonly bigint[];
+ result: ObjcSwiftMetadata;
+ visitor: SwiftNominalVisitor;
+}): FacetDecodeFacts => {
+ const { readers: read, result, visitor } = input;
+ const issues = [] as ReturnType<typeof issue>[];
+ const contexts = new Map<bigint, ContextFacts>();
+ const names = new Map<bigint, string>();
+ let examined = 0;
+ let decoded = 0;
+
+ const typeName = (descriptor: bigint): string => {
+ const known = names.get(descriptor);
+ if (known !== undefined) return known;
+ const value = read.relative(descriptor + 8n, "typeName");
+ if (value.kind !== "target")
+ throw new RangeError(unresolvedSwiftRelativeReason(value, "typeName"));
+ const name = read.string(value.target);
+ if (name.length === 0)
+ throw new RangeError("Swift type descriptor name is empty");
+ names.set(descriptor, name);
+ return name;
+ };
+
+ const parentOf = (context: bigint, walk: number): ContextFacts => {
+ const value = read.relative(context + 4n, "contextParent");
+ if (value.kind === "target") return contextOf(value.target, walk + 1);
+ return unresolved(
+ value.kind === "null"
+ ? "Swift context descriptor has no parent module"
+ : unresolvedSwiftRelativeReason(value, "contextParent"),
+ );
+ };
+
+ /** One level below `parent`, bounded in depth and qualified-name length. */
+ const child = (
+ parent: ContextFacts,
+ facts: Partial<ContextFacts>,
+ ): ContextFacts => {
+ if (parent.depth + 1 > MAXIMUM_CONTEXT_DEPTH)
+ return { ...tooDeep(), walkLimited: parent.walkLimited };
+ const next = {
+ ...parent,
+ depth: parent.reason === null ? parent.depth + 1 : 0,
+ ...facts,
+ };
+ return next.path !== null &&
+ next.path.length > MAXIMUM_QUALIFIED_NAME_LENGTH
+ ? {
+ ...next,
+ path: null,
+ reason:
+ next.reason ??
+ `Swift qualified type name exceeds ${MAXIMUM_QUALIFIED_NAME_LENGTH} characters`,
+ }
+ : next;
+ };
+
+ const readContext = (context: bigint, walk: number): ContextFacts => {
+ const kind = read.u32(context) & 31;
+ switch (kind) {
+ case MODULE: {
+ const value = read.relative(context + 8n, "moduleName");
+ if (value.kind !== "target")
+ return unresolved(unresolvedSwiftRelativeReason(value, "moduleName"));
+ const module = read.string(value.target);
+ return module.length === 0
+ ? unresolved("Swift module context name is empty")
+ : {
+ module,
+ path: "",
+ depth: 1,
+ anonymous: false,
+ reason: null,
+ walkLimited: false,
+ };
+ }
+ case CLASS:
+ case STRUCT:
+ case ENUM: {
+ const name = typeName(context);
+ const parent = parentOf(context, walk);
+ return child(parent, {
+ path:
+ parent.path === null
+ ? null
+ : parent.path === ""
+ ? name
+ : `${parent.path}.${name}`,
+ });
+ }
+ case ANONYMOUS:
+ return child(parentOf(context, walk), { anonymous: true });
+ case EXTENSION: {
+ // The extended type is a mangled name, often in another module, so
+ // the declaring module is known but the qualified path is not.
+ const parent = parentOf(context, walk);
+ return child(parent, {
+ path: null,
+ reason:
+ parent.reason ??
+ "Swift type is declared in an extension whose extended type is not demangled",
+ });
+ }
+ default:
+ return unresolved(`Unsupported Swift context descriptor kind ${kind}`);
+ }
+ };
+
+ const contextOf = (context: bigint, walk: number): ContextFacts => {
+ const known = contexts.get(context);
+ if (known !== undefined) return known;
+ // Bound recursion on cyclic or over-deep chains; this stop depends on
+ // where the walk began, so neither it nor its descendants are cached.
+ if (walk > MAXIMUM_CONTEXT_DEPTH)
+ return { ...tooDeep(), walkLimited: true };
+ let facts: ContextFacts;
+ try {
+ facts = readContext(context, walk);
+ } catch (cause) {
+ const reason = expectedSwiftMetadataReadFailure(cause);
+ if (reason === null) throw cause;
+ facts = unresolved(reason);
+ }
+ if (!facts.walkLimited) contexts.set(context, facts);
+ return facts;
+ };
+
+ const accessorOf = (
+ descriptor: bigint,
+ ): { address: string | null; reason: string | null } => {
+ try {
+ const value = read.relative(descriptor + 12n, "typeAccessFunction");
+ if (value.kind === "null") return { address: null, reason: null };
+ if (value.kind !== "target")
+ return {
+ address: null,
+ reason: unresolvedSwiftRelativeReason(value, "typeAccessFunction"),
+ };
+ return read.executable(value.target)
+ ? { address: hex(value.target), reason: null }
+ : {
+ address: null,
+ reason: `Swift metadata accessor ${hex(value.target)} is not in executable mapped code`,
+ };
+ } catch (cause) {
+ const reason = expectedSwiftMetadataReadFailure(cause);
+ if (reason === null) throw cause;
+ return { address: null, reason };
+ }
+ };
+
+ for (const record of input.entries) {
+ if (!read.admit()) {
+ issues.push(
+ issue(
+ FACET,
+ "record_budget_exhausted",
+ "max_records_reached",
+ hex(record),
+ ),
+ );
+ break;
+ }
+ examined++;
+ let descriptor: bigint;
+ // Unknown until read; an unread kind may be a class.
+ let kind: number | null = null;
+ let flags: number;
+ let name: string;
+ try {
+ const value = read.relative(record, "typeMetadataRecord");
+ if (value.kind !== "target")
+ throw new RangeError(
+ unresolvedSwiftRelativeReason(value, "typeMetadataRecord"),
+ );
+ descriptor = value.target;
+ flags = read.u32(descriptor);
+ kind = flags & 31;
+ if (kind !== CLASS && kind !== STRUCT && kind !== ENUM) {
+ issues.push(
+ issue(
+ FACET,
+ "unsupported_type_descriptor_kind",
+ `Unsupported Swift type descriptor kind ${kind}`,
+ hex(record),
+ ),
+ );
+ continue;
+ }
+ name = typeName(descriptor);
+ } catch (cause) {
+ const message = expectedSwiftMetadataReadFailure(cause);
+ if (message === null) throw cause;
+ if (kind === null || kind === CLASS) visitor.failure({ record, message });
+ issues.push(issue(FACET, "type_decode_failed", message, hex(record)));
+ continue;
+ }
+ visitor.descriptor({ record, descriptor, flags, name });
+ const context = contextOf(descriptor, 0);
+ const accessor = accessorOf(descriptor);
+ const reason = context.reason ?? accessor.reason;
+ result.swift_decls.push({
+ kind:
+ kind === STRUCT
+ ? "struct"
+ : kind === ENUM
+ ? "enum"
+ : ((flags >>> 16) & CLASS_IS_ACTOR) !== 0
+ ? "actor"
+ : "class",
+ name,
+ qualified_name:
+ context.path === null || context.path === "" ? null : context.path,
+ module: context.module,
+ generic: (flags & GENERIC) !== 0,
+ anonymous_context: context.anonymous,
+ accessor_address: accessor.address,
+ location: read.location(descriptor),
+ decode:
+ reason === null
+ ? { status: "decoded", reason: null }
+ : { status: "partial", reason },
+ evidence: read.evidence(
+ record,
+ "Swift __swift5_types record of the nominal type descriptor at location",
+ ),
+ });
+ if (reason === null) decoded++;
+ else
+ issues.push(
+ issue(FACET, "type_context_unresolved", reason, hex(descriptor)),
+ );
+ }
+ return {
+ facet: FACET,
+ examined,
+ decoded,
+ exhaustive: issues.length === 0,
+ issues,
+ };
+};
diff --git a/src/native/AppleSwiftRelativePointer.test.ts b/src/native/AppleSwiftRelativePointer.test.ts
index 2d7d60e8d..0c5f2dbf8 100644
--- a/src/native/AppleSwiftRelativePointer.test.ts
+++ b/src/native/AppleSwiftRelativePointer.test.ts
@@ -98,7 +98,7 @@ it("resolves zero offsets for nonnullable fields to their own field address", ()
"protocolName",
"typeName",
"typeMetadataRecord",
- "classDescriptorName",
+ "moduleName",
] as const) {
expect(relative(0x20n, kind)).toEqual({ kind: "target", target: 0x20n });
}
diff --git a/src/native/AppleSwiftVtables.test.ts b/src/native/AppleSwiftVtables.test.ts
index ddb47fc98..24f490d6a 100644
--- a/src/native/AppleSwiftVtables.test.ts
+++ b/src/native/AppleSwiftVtables.test.ts
@@ -2,16 +2,32 @@ import { describe, expect, it } from "vitest";
import { objcSwiftMetadataSchema } from "../domain/native/objcSwiftMetadata.js";
import { pushDispatchCoverage } from "./AppleDispatchCoverage.js";
-import { decodeSwiftClassVtables } from "./AppleSwiftVtables.js";
+import { createSwiftClassVtableDecoder } from "./AppleSwiftVtables.js";
+import { decodeSwiftNominalTypes } from "./AppleSwiftNominalTypes.js";
import { decodeSwiftDispatchFacets } from "./AppleSwiftDispatchFacets.js";
import type { DispatchRecordBudget } from "./AppleSwiftDispatchFacets.js";
import { issue } from "./AppleDispatchDecodeFacts.js";
it("preserves unsupported type-metadata tag reasons instead of reporting null", () => {
const result = objcSwiftMetadataSchema.parse({ db_save_result: null });
- const facts = decodeSwiftClassVtables({
+ const vtables = createSwiftClassVtableDecoder({
+ result,
+ readers: {
+ u32: () => 0,
+ relative: () => ({ kind: "null" }),
+ location: (address) => ({
+ address: `0x${address.toString(16)}`,
+ file_offset: Number(address),
+ }),
+ evidence: () => [],
+ executable: () => false,
+ admit: () => true,
+ },
+ });
+ const nominal = decodeSwiftNominalTypes({
entries: [0x100n],
result,
+ visitor: vtables.visitor,
readers: {
u32: () => 0,
relative: () => ({
@@ -28,11 +44,19 @@ it("preserves unsupported type-metadata tag reasons instead of reporting null",
admit: () => true,
},
});
+ const facts = vtables.facts();
+ expect(nominal.issues).toMatchObject([
+ {
+ code: "type_decode_failed",
+ message: "Unsupported Swift type metadata record tag 2",
+ },
+ ]);
expect(facts.issues).toMatchObject([
{
code: "vtable_decode_failed",
message: "Unsupported Swift type metadata record tag 2",
+ location: "0x100",
},
]);
expect(facts.issues[0]?.message).not.toContain("Null Swift");
@@ -89,17 +113,11 @@ it("counts examined slots and reports an unresolved async slot", () => {
[0x21cn, 2], // descriptor positive words
[0x234n, 0x40], // async method flag
]);
- const facts = decodeSwiftClassVtables({
- entries: [0x100n],
+ const vtables = createSwiftClassVtableDecoder({
result,
readers: {
u32: (address) => values.get(address) ?? 0,
- relative: (address) => ({
- kind: "target",
- target:
- address === 0x100n ? 0x200n : address === 0x208n ? 0x300n : 0x400n,
- }),
- string: () => "Widget",
+ relative: () => ({ kind: "target", target: 0x400n }),
location: (address) => ({
address: `0x${address.toString(16)}`,
file_offset: Number(address),
@@ -120,6 +138,13 @@ it("counts examined slots and reports an unresolved async slot", () => {
admit: () => true,
},
});
+ vtables.visitor.descriptor({
+ record: 0x100n,
+ descriptor: 0x200n,
+ flags: 0x80000010,
+ name: "Widget",
+ });
+ const facts = vtables.facts();
expect(result.swift_dispatch_slots[0]?.decode.status).toBe("partial");
expect(result.swift_dispatch_slots[1]?.decode.status).toBe("decoded");
@@ -152,6 +177,13 @@ it("counts examined slots and reports an unresolved async slot", () => {
legacyBindStreams: 0,
unreadRebaseBytes: 0,
},
+ declarations: {
+ facet: "swift_declarations",
+ examined: 0,
+ decoded: 0,
+ exhaustive: true,
+ issues: [],
+ },
swift: {
facet: "swift_conformances_static_witness_slots",
examined: 0,
@@ -283,6 +315,13 @@ describe("Swift vtable coverage facts: unsupported pointer fixup coverage", () =
legacyBindStreams: 0,
unreadRebaseBytes: 0,
},
+ declarations: {
+ facet: "swift_declarations",
+ examined: 0,
+ decoded: 0,
+ exhaustive: true,
+ issues: [],
+ },
swift: {
facet: "swift_conformances_static_witness_slots",
examined: 0,
diff --git a/src/native/AppleSwiftVtables.ts b/src/native/AppleSwiftVtables.ts
index fa563cb01..1286e0885 100644
--- a/src/native/AppleSwiftVtables.ts
+++ b/src/native/AppleSwiftVtables.ts
@@ -9,59 +9,61 @@ import type {
} from "./AppleSwiftDispatchFacets.js";
import { unresolvedSwiftRelativeReason } from "./AppleSwiftDispatchFacets.js";
import { issue, type FacetDecodeFacts } from "./AppleDispatchDecodeFacts.js";
+import type {
+ SwiftNominalDescriptor,
+ SwiftNominalRecordFailure,
+ SwiftNominalVisitor,
+} from "./AppleSwiftNominalTypes.js";
/** Byte readers shared with the validated Mach-O metadata boundary. */
export interface SwiftMetadataReaders {
u32(address: bigint): number;
relative(address: bigint, kind: SwiftRelativeField): SwiftRelativeValue;
- string(address: bigint): string;
location(address: bigint): NativeMetadataLocation;
evidence(address: bigint, description: string): NativeMetadataEvidence[];
executable(address: bigint): boolean;
admit(): boolean;
}
-/** Decode non-generic, non-resilient Swift class vtable descriptors without instantiating metadata. */
-export const decodeSwiftClassVtables = (input: {
+/**
+ * Decode non-generic, non-resilient Swift class vtables from the shared
+ * nominal descriptors as each is read. A record whose kind or name is unknown
+ * may be a class, so it keeps vtable coverage partial.
+ */
+export const createSwiftClassVtableDecoder = (input: {
readers: SwiftMetadataReaders;
- entries: readonly bigint[];
result: ObjcSwiftMetadata;
-}): FacetDecodeFacts => {
+}): { visitor: SwiftNominalVisitor; facts(): FacetDecodeFacts } => {
const { readers: read, result } = input;
- const failures: string[] = [];
const issues = [] as ReturnType<typeof issue>[];
// Coverage counts vtable slots, matching `decoded`; descriptor entries are
// a discovery input and are not slot records.
let examined = 0;
let decoded = 0;
- for (const field of input.entries) {
- if (!read.admit()) {
- failures.push("max_records_reached");
- issues.push(
- issue(
- "swift_class_vtable_descriptors",
- "record_budget_exhausted",
- "max_records_reached",
- `0x${field.toString(16)}`,
- ),
- );
- break;
- }
+ const failure = ({ record, message }: SwiftNominalRecordFailure): void => {
+ issues.push(
+ issue(
+ "swift_class_vtable_descriptors",
+ "vtable_decode_failed",
+ message,
+ `0x${record.toString(16)}`,
+ ),
+ );
+ };
+ const descriptor = ({
+ record,
+ descriptor,
+ flags,
+ name: owner,
+ }: SwiftNominalDescriptor): void => {
+ if ((flags & 31) !== 16) return;
try {
- const descriptorValue = read.relative(field, "typeMetadataRecord");
- if (descriptorValue.kind !== "target")
- throw new RangeError(
- unresolvedSwiftRelativeReason(descriptorValue, "typeMetadataRecord"),
- );
- const descriptor = descriptorValue.target;
- const flags = read.u32(descriptor);
- if ((flags & 31) !== 16) continue;
const specific = flags >>> 16;
if ((flags & 0x80) !== 0 || (specific & 0x2000) !== 0)
throw new TypeError(
"Generic class or resilient superclass metadata is unsupported",
);
- if ((specific & 0x8000) === 0) continue;
+ if ((specific & 0x8000) === 0) return;
const initialization = specific & 3;
if (initialization === 3)
throw new TypeError("Unknown metadata initialization kind");
@@ -76,21 +78,9 @@ export const decodeSwiftClassVtables = (input: {
throw new RangeError(
"Swift vtable count or offset exceeds declared metadata bounds",
);
- const ownerValue = read.relative(descriptor + 8n, "classDescriptorName");
- if (ownerValue.kind !== "target")
- throw new RangeError(
- unresolvedSwiftRelativeReason(ownerValue, "classDescriptorName"),
- );
- const ownerAddress = ownerValue.target;
- const owner = read.string(ownerAddress);
- if (owner.length === 0)
- throw new RangeError(
- "Swift class vtable descriptor class name is empty",
- );
for (let index = 0; index < count; index++) {
const entry = header + 8n + BigInt(index * 8);
if (!read.admit()) {
- failures.push("max_records_reached");
issues.push(
issue(
"swift_class_vtable_descriptors",
@@ -164,9 +154,6 @@ export const decodeSwiftClassVtables = (input: {
);
}
if ((specific & 0x4000) !== 0) {
- failures.push(
- `${owner}: inherited override descriptors are unsupported`,
- );
issues.push(
issue(
"swift_class_vtable_descriptors",
@@ -178,22 +165,24 @@ export const decodeSwiftClassVtables = (input: {
}
} catch (cause) {
const message = cause instanceof Error ? cause.message : String(cause);
- failures.push(`0x${field.toString(16)}: ${message}`);
issues.push(
issue(
"swift_class_vtable_descriptors",
"vtable_decode_failed",
message,
- `0x${field.toString(16)}`,
+ `0x${record.toString(16)}`,
),
);
}
- }
+ };
return {
- facet: "swift_class_vtable_descriptors",
- examined,
- decoded,
- exhaustive: issues.length === 0,
- issues,
+ visitor: { descriptor, failure },
+ facts: () => ({
+ facet: "swift_class_vtable_descriptors",
+ examined,
+ decoded,
+ exhaustive: issues.length === 0,
+ issues,
+ }),
};
};
diff --git a/tests/conformance/native/dispatch.swift b/tests/conformance/native/dispatch.swift
index 30a904a2f..5946b85be 100644
--- a/tests/conformance/native/dispatch.swift
+++ b/tests/conformance/native/dispatch.swift
@@ -10,3 +10,15 @@ public class ReaVtableFixture {
public init() {}
public func fixtureValue() -> Int { 23 }
}
+
+public enum ReaDeclFixtureEnum { case first, second(Int) }
+public struct ReaDeclFixtureOuter {
+ public struct Inner { public init() {} }
+}
+public struct ReaDeclFixtureGeneric<Value> {
+ public var value: Value
+ public init(_ value: Value) { self.value = value }
+}
+public actor ReaDeclFixtureActor {
+ public init() {}
+}