Files
reverse-engineering-anything/src/native/AppleDispatchMetadata.test.ts
T
Lewis WangandClaude Opus 5.5 86c27a9b55 fix(native): report ivar layouts that a Swift initializer assigns at load as unknown (#15095)
* fix(native): report ivar layouts that a Swift initializer assigns at load as unknown

A Swift class whose field layout is not fixed at compile time, for
example one holding an @Observable registrar or another resilient type,
sets RO_HAS_SWIFT_INITIALIZER in its class_ro_t. Swift stores 0 as the
placeholder offset of each field without a fixed offset, and size 0 and
alignment 1 for a field type without a fixed layout. The metadata
initializer writes the real values at load. inspect_native_dispatch_metadata
reported those placeholders as decoded offsets and sizes.

In such a class, a stored offset of 0 is now a null offset, and a
stored size of 0 nulls size, alignment and type encoding, which the
initializer replaces together. The row is partial with
ivar_layout_assigned_at_load. Classes without the flag keep their stored
values, including a genuine zero offset. The reader profile becomes
apple-metadata-reader-6 so earlier snapshots are not replayed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(native): state that a zero-size Swift field has placeholder bytes

In a class with RO_HAS_SWIFT_INITIALIZER, Swift stores a field of a
zero-size type such as Void with offset 0, size 0 and alignment 1, the
same bytes as a field whose layout the initializer assigns at load.
ivar_t does not record the field's type, so its size stays unknown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:06:25 -05:00

3734 lines
126 KiB
TypeScript

import {
CPU,
fatImage,
fatSliceRange,
} from "../artifacts/apple/MachoImage.fixture.js";
import { malformedInput } from "../domain/parseFailure.js";
import { describe, expect, it } from "vitest";
import { machoWithPropertyAttributes } from "../../tests/fixtures/objcPropertyMacho.js";
import { objcRecordBudgetMacho } from "../../tests/fixtures/objcRecordBudgetMacho.js";
import { decodeAppleDispatchMetadata } from "./AppleDispatchMetadata.fixture.js";
import { decodeObjcDispatchFacets } from "./AppleObjcDispatchFacets.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
/** The slice-selection refusal an admitted decode reports as REA's inconsistency. */
const refusalOf = (decode: () => unknown) => {
try {
decode();
} catch (cause) {
expect(cause).toBeInstanceOf(ProviderAdapterError);
return (cause as ProviderAdapterError).diagnostics;
}
throw new Error("expected the decode to be refused");
};
const base = 0x100000000n;
const fixture = (
relative = false,
category?: "partial-method" | "unmapped-pointer" | "unmapped-class",
) => {
const bytes = Buffer.alloc(4096);
const u32 = (offset: number, value: number) =>
bytes.writeUInt32LE(value, offset);
const ptr = (offset: number, target: number) =>
bytes.writeBigUInt64LE(base + BigInt(target), offset);
u32(0, 0xfeedfacf);
u32(4, 0x0100000c);
u32(16, 1);
u32(20, category === undefined ? 152 : 232);
u32(32, 0x19);
u32(36, category === undefined ? 152 : 232);
bytes.write("__DATA", 40);
ptr(56, 0);
bytes.writeBigUInt64LE(4096n, 64);
bytes.writeBigUInt64LE(4096n, 80);
u32(92, 5);
u32(96, category === undefined ? 1 : 2);
bytes.write("__objc_classlist", 104);
bytes.write("__DATA", 120);
ptr(136, 0x180);
bytes.writeBigUInt64LE(8n, 144);
if (category !== undefined) {
bytes.write("__objc_catlist", 184);
bytes.write("__DATA", 200);
ptr(216, 0xb00);
bytes.writeBigUInt64LE(8n, 224);
u32(232, 0xb00);
}
u32(152, 0x180);
ptr(0x180, 0x200);
ptr(0x200, 0x280);
ptr(0x220, 0x300);
ptr(0x2a0, 0x380);
u32(0x308, 16);
ptr(0x318, 0x450);
ptr(0x320, 0x480);
ptr(0x330, 0x500);
ptr(0x328, 0x700);
ptr(0x340, 0x600);
u32(0x380, 1);
ptr(0x398, 0x450);
bytes.write("Fixture\0", 0x450);
bytes.write("performAction:\0", 0x460);
u32(0x480, relative ? 0xc000000c : 24);
u32(0x484, 1);
if (relative) {
bytes.writeInt32LE(0x460 - 0x488, 0x488);
bytes.writeInt32LE(0x5c0 - 0x48c, 0x48c);
bytes.writeInt32LE(0x700 - 0x490, 0x490);
} else {
ptr(0x488, 0x460);
ptr(0x490, 0x5c0);
ptr(0x498, 0x700);
}
u32(0x500, 32);
u32(0x504, 1);
ptr(0x508, 0x580);
ptr(0x510, 0x5a0);
ptr(0x518, 0x5c0);
u32(0x580, 8);
bytes.write("state\0", 0x5a0);
bytes.write("i\0", 0x5c0);
u32(0x600, 16);
u32(0x604, 3);
ptr(0x608, 0x640);
ptr(0x610, 0x650);
ptr(0x618, 0x660);
ptr(0x620, 0x670);
ptr(0x628, 0x680);
ptr(0x630, 0x690);
bytes.write("atomicValue\0", 0x640);
bytes.write("Tq\0", 0x650);
bytes.write("nonatomicValue\0", 0x660);
bytes.write("Tq,N\0", 0x670);
bytes.write("unknownValue\0", 0x680);
bytes.writeBigUInt64LE(1n, 0x700);
ptr(0x708, 0x740);
ptr(0x748, 0x900);
ptr(0x758, 0x800);
ptr(0x768, 0x840);
u32(0x780, 72);
u32(0x800, 24);
u32(0x804, 1);
ptr(0x808, 0x920);
u32(0x840, 24);
u32(0x844, 1);
ptr(0x848, 0x940);
bytes.write("FixtureProtocol\0", 0x900);
bytes.write("requiredAction:\0", 0x920);
bytes.write("optionalAction:\0", 0x940);
if (category !== undefined) {
if (category === "unmapped-pointer") {
bytes.writeBigUInt64LE(0xffffffffffffffffn, 0xb00);
} else {
ptr(0xb00, 0xb40);
ptr(0xb40, 0xbc0);
if (category === "unmapped-class") ptr(0xb48, 0x5000);
else ptr(0xb48, 0x200);
ptr(0xb50, 0xb80);
u32(0xb80, 24);
u32(0xb84, 1);
ptr(0xb88, 0x460);
ptr(0xb90, 0x5c0);
if (category === "unmapped-class") ptr(0xb98, 0x700);
else bytes.writeBigUInt64LE(0xffffffffffffffffn, 0xb98);
bytes.write("FixtureCategory\0", 0xbc0);
}
}
return bytes;
};
const provenance = { path: "/fixture/app", sha256: "a".repeat(64) };
describe("decoded Objective-C property attributes", () => {
it("retains quoted class names, ownership and accessors", () => {
const result = decodeAppleDispatchMetadata(
machoWithPropertyAttributes(
'T@"NSString<NSCopying, NSSecureCoding>",C,N,GcustomTitle,V_title',
{ firstName: "title" },
),
100,
provenance,
);
expect(result.objc_classes[0]?.properties).toEqual(
["title", "second"].map((name) => ({
name,
type_encoding: '@"NSString<NSCopying, NSSecureCoding>"',
atomicity: "nonatomic",
attributes: [
{ name: "T", value: '@"NSString<NSCopying, NSSecureCoding>"' },
{ name: "C", value: "" },
{ name: "N", value: "" },
{ name: "G", value: "customTitle" },
{ name: "V", value: "_title" },
],
is_readonly: false,
getter: "customTitle",
setter: null,
})),
);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({ status: "complete", reason: null });
});
it.each([
["Tq,R", "q", "atomic"],
["Tq,R,N", "q", "nonatomic"],
["R", null, null],
] as const)(
"preserves readonly flags and established atomicity for %s",
(attributes, typeEncoding, atomicity) => {
const result = decodeAppleDispatchMetadata(
machoWithPropertyAttributes(attributes),
100,
provenance,
);
expect(result.objc_classes[0]?.properties).toMatchObject(
["first", "second"].map((name) => ({
name,
type_encoding: typeEncoding,
atomicity,
is_readonly: true,
})),
);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({ status: "complete", reason: null });
},
);
it.each([
[
"an unfinished quoted class name",
'T@"NSString,N,R',
'@"NSString,N,R',
null,
null,
],
[
"flags before an unfinished quote",
'N,R,T@"NSString',
'@"NSString',
"nonatomic",
true,
],
[
"an unfinished template argument",
"T{vector<float, float,N,R",
"{vector<float, float,N,R",
null,
null,
],
] as const)(
"retains established flags and reports both properties with %s",
(_, attributes, typeEncoding, atomicity, readonly) => {
const result = decodeAppleDispatchMetadata(
machoWithPropertyAttributes(attributes),
100,
provenance,
);
expect(result.objc_classes[0]?.properties).toMatchObject(
["first", "second"].map((name) => ({
name,
type_encoding: typeEncoding,
atomicity,
is_readonly: readonly,
})),
);
const coverage = result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
);
expect(coverage).toMatchObject({ status: "partial" });
expect(coverage?.reason).toContain(
"property_attributes_incomplete at 0x100000508: Fixture: property first",
);
expect(coverage?.reason).toContain(
"property_attributes_incomplete at 0x100000518: Fixture: property second",
);
expect(
coverage?.reason?.match(/property_attributes_incomplete at /gu),
).toHaveLength(2);
},
);
});
it("retains Objective-C++ template commas in decoded property facts", () => {
const attributes = "T{vector<float, float, float>=},N,V_position";
const result = decodeAppleDispatchMetadata(
machoWithPropertyAttributes(attributes),
100,
provenance,
);
expect(result.objc_classes[0]?.properties).toEqual(
["first", "second"].map((name) => ({
name,
type_encoding: "{vector<float, float, float>=}",
atomicity: "nonatomic",
attributes: [
{ name: "T", value: "{vector<float, float, float>=}" },
{ name: "N", value: "" },
{ name: "V", value: "_position" },
],
is_readonly: false,
getter: null,
setter: null,
})),
);
expect(
result.coverage.find(({ facet }) => facet === "objc_properties_categories"),
).toMatchObject({ status: "complete" });
});
it("retains duplicate encoded method candidates without choosing one class-method address", () => {
const bytes = objcRecordBudgetMacho("class", [0x700, 0x720]);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(
result.objc_dispatch_implementations.map(
({ implementation_address }) => implementation_address,
),
).toEqual(["0x100000700", "0x100000720"]);
expect(result.objc_classes[0]?.methods).toEqual([
{
selector: "classMethod",
method_type: "instance",
address: null,
is_required: null,
is_optional: null,
},
]);
});
const swiftExternalSwiftBindingImage = (
boundField: "protocol" | "type" | "objc-class" = "protocol",
) => {
const bytes = fixture();
const sectionCommand = 32;
bytes.writeUInt32LE(232, sectionCommand + 4);
bytes.writeUInt32LE(2, sectionCommand + 64);
bytes.write("__swift5_proto", 184);
bytes.write("__DATA", 200);
bytes.writeBigUInt64LE(base + 0xa00n, 216);
bytes.writeBigUInt64LE(4n, 224);
bytes.writeUInt32LE(0xa00, 232);
bytes.writeUInt32LE(2, 236);
const dyldInfo = sectionCommand + 232;
bytes.writeUInt32LE(0x80000022, dyldInfo);
bytes.writeUInt32LE(48, dyldInfo + 4);
bytes.writeUInt32LE(0xf00, dyldInfo + 16);
const bind = Buffer.from([
0x11, // SET_DYLIB_ORDINAL_IMM 1
0x40,
...Buffer.from(
`${boundField === "protocol" ? "_$sSQMp" : boundField === "objc-class" ? "_OBJC_CLASS_$_NSObject" : "_$sSiMn"}\0`,
),
0x51, // SET_TYPE_IMM pointer
0x70,
0x80,
0x16, // SET_SEGMENT_AND_OFFSET_ULEB segment 0 + offset 0xb00
0x90,
0x00,
]);
bytes.writeUInt32LE(bind.length, dyldInfo + 20);
const dylibCommand = dyldInfo + 48;
bytes.writeUInt32LE(0xc, dylibCommand); // LC_LOAD_DYLIB
bytes.writeUInt32LE(56, dylibCommand + 4);
bytes.writeUInt32LE(24, dylibCommand + 8);
bytes.write("/usr/lib/libswiftCore.dylib\0", dylibCommand + 24);
bytes.writeUInt32LE(3, 16); // segment, dyld info, and dependent dylib
bytes.writeUInt32LE(336, 20);
bind.copy(bytes, 0xf00);
// Conformance at 0xa10: one reference is an indirect relative pointer to
// the import slot at 0xb00; the sibling reference points to local metadata.
bytes.writeInt32LE(0x10, 0xa00);
bytes.writeInt32LE(boundField === "protocol" ? 0x1ec : 0xec, 0xa14);
bytes.writeInt32LE(0, 0xa18); // Nullable witness-table pattern.
bytes.writeUInt32LE(
boundField === "protocol" ? 0 : boundField === "objc-class" ? 24 : 8,
0xa1c,
);
bytes.writeInt32LE(boundField === "protocol" ? 0xf1 : 0x2f0, 0xa10); // Protocol reference: imported indirect slot or local descriptor.
bytes.writeBigUInt64LE(0n, 0xb00); // Bound slot has no in-image pointer.
bytes.writeUInt32LE(16, 0xc00);
bytes.writeInt32LE(0x1f8, 0xc08);
bytes.writeInt32LE(0xc40 - 0xc04, 0xc04);
bytes.writeUInt32LE(0, 0xc40);
bytes.writeInt32LE(0xe40 - 0xc48, 0xc48);
bytes.write("FixtureModule\0", 0xe40);
if (boundField !== "protocol") {
bytes.writeUInt32LE(3, 0xd00);
bytes.writeInt32LE(0xc40 - 0xd04, 0xd04);
bytes.writeInt32LE(0xf8, 0xd08);
bytes.write("Equatable\0", 0xe00);
} else {
bytes.write("Widget\0", 0xe00);
}
return bytes;
};
const swiftBoundWitnessSlotImage = () => {
const bytes = fixture();
const sectionCommand = 32;
bytes.writeUInt32LE(232, sectionCommand + 4);
bytes.writeUInt32LE(2, sectionCommand + 64);
bytes.write("__swift5_proto", 184);
bytes.write("__DATA", 200);
bytes.writeBigUInt64LE(base + 0xa00n, 216);
bytes.writeBigUInt64LE(4n, 224);
bytes.writeUInt32LE(0xa00, 232);
bytes.writeUInt32LE(2, 236);
const dyldInfo = sectionCommand + 232;
bytes.writeUInt32LE(0x80000022, dyldInfo);
bytes.writeUInt32LE(48, dyldInfo + 4);
bytes.writeUInt32LE(0xf20, dyldInfo + 8);
bytes.writeUInt32LE(6, dyldInfo + 12);
bytes.writeUInt32LE(0xf00, dyldInfo + 16);
const bind = Buffer.from([
0x11,
0x40,
...Buffer.from("_externalWitnessImpl\0"),
0x51, // SET_TYPE_IMM pointer
0x70,
0x88,
0x1c, // SET_SEGMENT_AND_OFFSET_ULEB segment 0 + witness slot 0xe08
0x90,
0x00,
]);
bytes.writeUInt32LE(bind.length, dyldInfo + 20);
const dylibCommand = dyldInfo + 48;
bytes.writeUInt32LE(0xc, dylibCommand);
bytes.writeUInt32LE(56, dylibCommand + 4);
bytes.writeUInt32LE(24, dylibCommand + 8);
bytes.write("/usr/lib/libswiftCore.dylib\0", dylibCommand + 24);
bytes.writeUInt32LE(3, 16);
bytes.writeUInt32LE(336, 20);
bind.copy(bytes, 0xf00);
// One unrelated, valid local rebase proves unmatched structural pointers
// stay known-raw after the complete legacy stream is walked.
Buffer.from([0x11, 0x20, 0xa0, 0x1c, 0x51, 0]).copy(bytes, 0xf20);
bytes.writeInt32LE(0x10, 0xa00);
bytes.writeInt32LE(0x1ec, 0xa14);
bytes.writeInt32LE(0x3e8, 0xa18);
bytes.writeUInt32LE(0, 0xa1c);
bytes.writeInt32LE(0x2f0, 0xa10);
bytes.writeUInt32LE(16, 0xc00);
bytes.writeInt32LE(0x238, 0xc08);
bytes.writeInt32LE(0xc40 - 0xc04, 0xc04);
bytes.writeUInt32LE(0, 0xc40);
bytes.writeInt32LE(0xec0 - 0xc48, 0xc48);
bytes.write("FixtureModule\0", 0xec0);
bytes.writeUInt32LE(3, 0xd00);
bytes.writeInt32LE(0xc40 - 0xd04, 0xd04);
bytes.writeInt32LE(0x148, 0xd08);
bytes.writeUInt32LE(0, 0xd0c);
bytes.writeUInt32LE(1, 0xd10);
bytes.writeUInt32LE(1, 0xd18);
bytes.writeBigUInt64LE(base + 0xa10n, 0xe00);
bytes.write("Widget\0", 0xe40);
bytes.write("Equatable\0", 0xe50);
return bytes;
};
const swiftConformanceTypeReferenceImage = (
typeKind: number,
input: {
readonly typeTargetOffset?: number;
readonly indirectClassTargetOffset?: number;
} = {},
) => {
const bytes = swiftBoundWitnessSlotImage();
const typeTargetOffset = input.typeTargetOffset ?? 0xe60;
bytes.writeUInt32LE(typeKind << 3, 0xa1c);
bytes.writeInt32LE(typeTargetOffset - 0xa14, 0xa14);
if (typeKind === 2 && typeTargetOffset === 0xe60) {
bytes.write("NSObject\0", typeTargetOffset);
} else if (typeKind === 3 && typeTargetOffset === 0xe60) {
bytes.writeBigUInt64LE(
base + BigInt(input.indirectClassTargetOffset ?? 0xe80),
typeTargetOffset,
);
}
return bytes;
};
describe("Imported class symbol byte identities", () => {
it.each(["invalid bytes", "literal replacement character"] as const)(
"keeps imported class identity distinct for %s",
(nameKind) => {
const bytes = swiftExternalSwiftBindingImage("objc-class");
const nameAt = 0xf02;
const literalName = "_OBJC_CLASS_$_�bject";
if (nameKind === "invalid bytes")
bytes[nameAt + Buffer.byteLength("_OBJC_CLASS_$_")] = 0xff;
else Buffer.from(literalName).copy(bytes, nameAt);
const result = decodeAppleDispatchMetadata(
bytes,
100,
provenance,
"arm64",
["0x100000b00"],
true,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: null,
type_reference_kind: 3,
protocol_name: "Equatable",
type_binding:
nameKind === "invalid bytes" ? null : { symbol: literalName },
decode: { status: "partial" },
},
]);
expect(result.objc_class_import_bindings).toEqual(
nameKind === "invalid bytes"
? []
: [expect.objectContaining({ symbol: literalName })],
);
expect(result.objc_class_import_binding_coverage).toMatchObject({
status: nameKind === "invalid bytes" ? "partial" : "complete",
});
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toMatchObject({
status: nameKind === "invalid bytes" ? "partial" : "complete",
});
if (nameKind === "invalid bytes")
expect(result.objc_class_import_binding_coverage?.reason).toContain(
"UTF-8",
);
},
);
});
describe("Imported class symbol candidate completeness", () => {
it("reports binding coverage unknown when the caller does not state the candidates are complete", () => {
const result = decodeAppleDispatchMetadata(
swiftExternalSwiftBindingImage("objc-class"),
100,
provenance,
"arm64",
["0x100000b00"],
);
expect(result.objc_class_import_bindings).toEqual([
expect.objectContaining({ symbol: "_OBJC_CLASS_$_NSObject" }),
]);
expect(result.objc_class_import_binding_coverage).toMatchObject({
status: "unknown",
reason: expect.stringContaining("objc_class_import_addresses_complete"),
});
});
});
describe("Imported library byte identities", () => {
it.each(["invalid bytes", "literal replacement character"] as const)(
"keeps Swift and Objective-C library identity distinct for %s",
(nameKind) => {
const bytes = swiftExternalSwiftBindingImage("objc-class");
const nameAt = 32 + 232 + 48 + 24;
bytes.fill(0, nameAt, nameAt + 32);
const name =
nameKind === "invalid bytes"
? Buffer.from([0x2f, 0x6c, 0x69, 0x62, 0x80])
: Buffer.from("/lib�");
name.copy(bytes, nameAt);
const result = decodeAppleDispatchMetadata(
bytes,
100,
provenance,
"arm64",
["0x100000b00"],
true,
);
expect(result.swift_conformances).toMatchObject([
{
protocol_name: "Equatable",
type_binding:
nameKind === "invalid bytes"
? null
: { symbol: "_OBJC_CLASS_$_NSObject", library: "/lib�" },
decode: { status: "partial" },
},
]);
expect(result.objc_class_import_bindings).toEqual(
nameKind === "invalid bytes"
? []
: [expect.objectContaining({ library: "/lib�" })],
);
expect(result.objc_class_import_binding_coverage).toMatchObject({
status: nameKind === "invalid bytes" ? "partial" : "complete",
});
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toMatchObject({
status: nameKind === "invalid bytes" ? "partial" : "complete",
});
expect(result.objc_classes[0]?.name).toBe("Fixture");
if (nameKind === "invalid bytes")
expect(result.objc_class_import_binding_coverage?.reason).toContain(
"install-name bytes",
);
},
);
});
describe("Swift imported protocol references", () => {
it("preserves bind identity without reading VM address zero and marks coverage partial", () => {
const result = decodeAppleDispatchMetadata(
swiftExternalSwiftBindingImage(),
100,
provenance,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: "Widget",
protocol_name: null,
protocol_binding: {
symbol: "_$sSQMp",
requested_address: "0x100000b00",
},
decode: { status: "partial" },
},
]);
expect(
result.relative_pointers.find(
({ field }) => field.address === "0x100000a10",
),
).toMatchObject({
target: { address: null, file_offset: null },
binding: { symbol: "_$sSQMp" },
decode: { status: "partial" },
});
expect(
result.coverage.find(
({ facet }) => facet === "swift_conformances_static_witness_slots",
),
).toMatchObject({ status: "partial" });
});
it("preserves an indirect imported type reference as a typed binding", () => {
const result = decodeAppleDispatchMetadata(
swiftExternalSwiftBindingImage("type"),
100,
provenance,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: null,
type_reference_kind: 1,
type_binding: {
symbol: "_$sSiMn",
requested_address: "0x100000b00",
},
protocol_name: "Equatable",
protocol_binding: null,
decode: { status: "partial" },
},
]);
expect(
result.coverage.find(
({ facet }) => facet === "swift_conformances_static_witness_slots",
),
).toMatchObject({ status: "partial" });
});
it("preserves a kind-3 Objective-C class import without inventing a class name", () => {
const result = decodeAppleDispatchMetadata(
swiftExternalSwiftBindingImage("objc-class"),
100,
provenance,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: null,
type_reference_kind: 3,
type_reference_target: { address: null, file_offset: null },
type_binding: {
symbol: "_OBJC_CLASS_$_NSObject",
requested_address: "0x100000b00",
},
protocol_name: "Equatable",
decode: { status: "partial" },
},
]);
});
it("reports only the legacy stream mechanisms actually examined", () => {
const bytes = swiftBoundWitnessSlotImage();
const dyldInfo = 32 + 232;
bytes.writeUInt32LE(0, dyldInfo + 16);
bytes.writeUInt32LE(0, dyldInfo + 20);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toEqual({
facet: "pointer_fixups",
status: "complete",
reason: "LC_DYLD_INFO rebase opcodes",
examined: 1,
decoded: 1,
});
});
it("retains an unmatched local witness header beside a legacy rebase and preserves a bound implementation", () => {
const result = decodeAppleDispatchMetadata(
swiftBoundWitnessSlotImage(),
100,
provenance,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: "Widget",
type_reference_kind: 0,
type_reference_target: { address: "0x100000c00", file_offset: 3072 },
protocol_name: "Equatable",
witness_table: { address: "0x100000e00" },
decode: { status: "decoded" },
},
]);
expect(result.swift_dispatch_slots).toMatchObject([
{
table_kind: "witness_table",
slot_index: 1,
implementation_address: null,
implementation_binding: {
symbol: "_externalWitnessImpl",
requested_address: "0x100000e08",
},
decode: { status: "partial" },
},
]);
expect(
result.coverage.find(
({ facet }) => facet === "swift_conformances_static_witness_slots",
),
).toMatchObject({ status: "partial" });
});
});
describe("Swift conformance type-reference kinds", () => {
it.each([
{
label: "zero rebase",
target: 0n,
rebase: true,
address: "0x0",
fileOffset: 0,
},
{
label: "nonzero rebase",
target: 0x100n,
rebase: true,
address: "0x100",
fileOffset: 256,
},
{
label: "unmapped rebase",
target: 0x800n,
rebase: true,
address: "0x800",
fileOffset: null,
},
{
label: "raw zero",
target: 0n,
rebase: false,
address: null,
fileOffset: null,
},
{
label: "raw nonzero",
target: 0x100n,
rebase: false,
address: "0x100",
fileOffset: 256,
},
])(
"preserves kind-3 target identity for $label",
({ target, rebase, address, fileOffset }) => {
const bytes = Buffer.alloc(1024);
bytes.writeUInt32LE(0xfeedfacf, 0);
bytes.writeUInt32LE(0x0100000c, 4);
bytes.writeUInt32LE(6, 12); // MH_DYLIB; read statically, never executed.
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(200, 20);
bytes.writeUInt32LE(0x19, 32); // LC_SEGMENT_64, mapping address zero.
bytes.writeUInt32LE(152, 36);
bytes.write("__TEXT", 40);
bytes.writeBigUInt64LE(1024n, 64);
bytes.writeBigUInt64LE(1024n, 80);
bytes.writeUInt32LE(5, 88);
bytes.writeUInt32LE(5, 92);
bytes.writeUInt32LE(1, 96);
bytes.write("__swift5_proto", 104);
bytes.write("__TEXT", 120);
bytes.writeBigUInt64LE(0x200n, 136);
bytes.writeBigUInt64LE(4n, 144);
bytes.writeUInt32LE(0x200, 152);
bytes.writeUInt32LE(2, 156);
bytes.writeUInt32LE(0x80000022, 184); // LC_DYLD_INFO_ONLY.
bytes.writeUInt32LE(48, 188);
if (rebase) {
bytes.writeUInt32LE(0x380, 192);
bytes.writeUInt32LE(6, 196);
// Pointer rebase at segment 0 + 0x300, then end the stream.
Buffer.from([0x11, 0x20, 0x80, 0x06, 0x51, 0x00]).copy(bytes, 0x380);
}
bytes.writeInt32LE(0x20, 0x200); // Conformance descriptor at 0x220.
bytes.writeInt32LE(0x40, 0x220); // Protocol descriptor at 0x260.
bytes.writeInt32LE(0xdc, 0x224); // Indirect class cell at 0x300.
bytes.writeUInt32LE(3 << 3, 0x22c);
bytes.writeUInt32LE(3, 0x260); // Protocol context descriptor.
bytes.writeInt32LE(0x320 - 0x264, 0x264); // Parent module context.
bytes.writeUInt32LE(0, 0x320);
bytes.writeInt32LE(0x340 - 0x328, 0x328);
bytes.write("FixtureModule\0", 0x340);
bytes.writeInt32LE(0x18, 0x268);
bytes.write("FixtureProtocol\0", 0x280);
bytes.writeBigUInt64LE(target, 0x300);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_reference_kind: 3,
type_reference_target: { address, file_offset: fileOffset },
type_name: null,
type_binding: null,
protocol_name: "FixtureProtocol",
protocol_target: { address: "0x260", file_offset: 608 },
witness_table: { address: null, file_offset: null },
decode: {
status: "partial",
reason: expect.stringMatching(
/indirect Objective-C class metadata.*runtime lookup/i,
),
},
},
]);
expect(result.swift_conformances).toHaveLength(1);
expect(result.swift_dispatch_slots).toEqual([]);
expect(result.relative_pointers).toContainEqual(
expect.objectContaining({
field: { address: "0x224", file_offset: 548 },
target: { address: "0x300", file_offset: 768 },
}),
);
},
);
it("keeps a direct Objective-C class name and its local witness evidence", () => {
const result = decodeAppleDispatchMetadata(
swiftConformanceTypeReferenceImage(2),
100,
provenance,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: "NSObject",
type_reference_kind: 2,
type_reference_target: { address: "0x100000e60", file_offset: 3680 },
protocol_name: "Equatable",
witness_table: { address: "0x100000e00" },
decode: { status: "decoded" },
},
]);
expect(result.swift_dispatch_slots[0]).toMatchObject({
owner: "NSObject: Equatable",
table_kind: "witness_table",
implementation_address: null,
implementation_binding: {
symbol: "_externalWitnessImpl",
requested_address: "0x100000e08",
},
});
});
});
describe("Swift partial conformance reference retention", () => {
it("retains type and witness facts when the protocol target is unmapped", () => {
const bytes = swiftConformanceTypeReferenceImage(2);
bytes.writeInt32LE(0x5000 - 0xa10, 0xa10);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_name: "NSObject",
type_reference_target: { address: "0x100000e60", file_offset: 3680 },
protocol_name: null,
protocol_target: { address: "0x100005000", file_offset: null },
witness_table: { address: "0x100000e00", file_offset: 3584 },
decode: { status: "partial" },
},
]);
expect(result.swift_dispatch_slots).toEqual([]);
});
it("preserves a typed type binding beside an unmapped protocol without a guessed name", () => {
const bytes = swiftExternalSwiftBindingImage("objc-class");
bytes.writeInt32LE(0x5000 - 0xa10, 0xa10);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_name: null,
type_reference_kind: 3,
type_reference_target: { address: null, file_offset: null },
type_binding: {
symbol: "_OBJC_CLASS_$_NSObject",
requested_address: "0x100000b00",
},
protocol_name: null,
protocol_target: { address: "0x100005000", file_offset: null },
decode: { status: "partial" },
},
]);
});
it("retains protocol and type targets when the protocol name is unmapped", () => {
const bytes = swiftConformanceTypeReferenceImage(2);
bytes.writeInt32LE(0x5000 - 0xd08, 0xd08);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_name: "NSObject",
protocol_name: null,
protocol_target: { address: "0x100000d00", file_offset: 3328 },
witness_table: { address: "0x100000e00", file_offset: 3584 },
decode: { status: "partial" },
},
]);
expect(result.swift_dispatch_slots).toEqual([]);
});
it("retains other facts when the protocol descriptor kind is unsupported", () => {
const bytes = swiftConformanceTypeReferenceImage(2);
bytes.writeUInt32LE(4, 0xd00);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_name: "NSObject",
protocol_name: null,
protocol_target: { address: "0x100000d00", file_offset: 3328 },
witness_table: { address: "0x100000e00", file_offset: 3584 },
decode: { status: "partial" },
},
]);
});
it("retains other facts when a protocol name is invalid UTF-8", () => {
const bytes = swiftConformanceTypeReferenceImage(2);
bytes.writeUInt8(0xff, 0xe50);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_name: "NSObject",
protocol_name: null,
protocol_target: { address: "0x100000d00", file_offset: 3328 },
witness_table: { address: "0x100000e00", file_offset: 3584 },
decode: { status: "partial" },
},
]);
});
it("retains mixed readable witness slots when a later slot is unmapped", () => {
const bytes = swiftConformanceTypeReferenceImage(2);
bytes.writeUInt32LE(2, 0xd10);
bytes.writeInt32LE(0xff0 - 0xa18, 0xa18);
bytes.writeBigUInt64LE(base + 0xa10n, 0xff0);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_name: "NSObject",
protocol_name: "Equatable",
witness_table: { address: "0x100000ff0", file_offset: 4080 },
},
]);
expect(result.swift_dispatch_slots).toMatchObject([
{
slot_index: 1,
location: { address: "0x100000ff8", file_offset: 4088 },
},
]);
expect(result.swift_dispatch_slots).toHaveLength(1);
expect(
result.coverage.find(
({ facet }) => facet === "swift_conformances_static_witness_slots",
),
).toMatchObject({ status: "partial" });
});
});
describe("Swift unresolved conformance type references", () => {
it.each([3, 4, 7] as const)(
"retains an unresolved type-reference kind %i with conformance and witness locations",
(typeKind) => {
const result = decodeAppleDispatchMetadata(
swiftConformanceTypeReferenceImage(typeKind),
100,
provenance,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: null,
type_reference_kind: typeKind,
...(typeKind === 3
? {
type_reference_target: {
address: "0x100000e80",
file_offset: 3712,
},
}
: {}),
protocol_name: "Equatable",
witness_table: { address: "0x100000e00" },
decode: { status: "partial" },
},
]);
expect(result.swift_dispatch_slots).toEqual([]);
expect(
result.coverage.find(
({ facet }) => facet === "swift_conformances_static_witness_slots",
),
).toMatchObject({ status: "partial" });
},
);
it("retains a kind-2 source location when its inline class name is empty", () => {
const bytes = swiftConformanceTypeReferenceImage(2);
bytes.writeUInt8(0, 0xe60);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances).toMatchObject([
{
type_name: null,
type_reference_kind: 2,
type_reference_target: { address: "0x100000e60", file_offset: 3680 },
protocol_name: "Equatable",
witness_table: { address: "0x100000e00" },
decode: { status: "partial" },
},
]);
expect(result.swift_dispatch_slots).toEqual([]);
});
it.each([
{ kind: 0, target: 0x5000, actual: 0x5000 },
{ kind: 1, target: 0x5000, actual: 0x5000 },
{ kind: 2, target: 0x5000, actual: 0x5000 },
{ kind: 3, target: 0x5000, actual: 0x5000 },
{
kind: 3,
target: 0xe60,
indirectClassTarget: 0x5000,
actual: 0x5000,
},
{ kind: 4, target: 0x5000, actual: 0x5000 },
])(
"retains partial conformance evidence when kind $kind targets non-file-backed address $target",
({ kind, target, indirectClassTarget, actual }) => {
const result = decodeAppleDispatchMetadata(
swiftConformanceTypeReferenceImage(kind, {
typeTargetOffset: target,
...(indirectClassTarget === undefined
? {}
: { indirectClassTargetOffset: indirectClassTarget }),
}),
100,
provenance,
);
expect(result.swift_conformances).toMatchObject([
{
type_name: null,
type_reference_kind: kind,
type_reference_target: {
address: `0x${(base + BigInt(actual)).toString(16)}`,
file_offset: null,
},
protocol_name: "Equatable",
witness_table: { address: "0x100000e00" },
decode: { status: "partial" },
},
]);
expect(result.swift_dispatch_slots).toEqual([]);
expect(
result.coverage.find(
({ facet }) => facet === "swift_conformances_static_witness_slots",
),
).toMatchObject({ status: "partial" });
},
);
});
const withProtocolListSection = (bytes: Buffer): Buffer => {
const pointer = (at: number, offset: number) =>
bytes.writeBigUInt64LE(base + BigInt(offset), at);
bytes.writeUInt32LE(232, 20);
bytes.writeUInt32LE(232, 36);
bytes.writeUInt32LE(2, 96);
bytes.write("__objc_protolist", 184);
bytes.write("__DATA", 200);
pointer(216, 0x6c0);
bytes.writeBigUInt64LE(8n, 224);
pointer(0x6c0, 0x740);
return bytes;
};
const partialSiblingsFixture = (
options: {
readonly emptyMiddleClass?: boolean;
} = {},
) => {
const bytes = Buffer.alloc(4096);
const imageBase = 0x100000000n;
bytes.writeUInt32LE(0xfeedfacf, 0);
bytes.writeUInt32LE(0x0100000c, 4);
bytes.writeUInt32LE(2, 12);
bytes.writeUInt32LE(1, 16);
bytes.writeUInt32LE(232, 20);
bytes.writeUInt32LE(0x19, 32);
bytes.writeUInt32LE(232, 36);
bytes.write("__DATA", 40);
bytes.writeBigUInt64LE(imageBase, 56);
bytes.writeBigUInt64LE(4096n, 64);
bytes.writeBigUInt64LE(4096n, 80);
bytes.writeUInt32LE(5, 92);
bytes.writeUInt32LE(2, 96);
bytes.write("__objc_classlist", 104);
bytes.writeBigUInt64LE(imageBase + 0x200n, 136);
bytes.writeBigUInt64LE(24n, 144);
bytes.write("__objc_protolist", 184);
bytes.writeBigUInt64LE(imageBase + 0x300n, 216);
bytes.writeBigUInt64LE(8n, 224);
for (const [slot, record, ro, name] of [
[0x200, 0x400, 0x500, 0x600],
[0x208, 0x440, 0x540, 0x620],
[0x210, 0x480, 0x580, 0x640],
] as const) {
bytes.writeBigUInt64LE(imageBase + BigInt(record), slot);
bytes.writeBigUInt64LE(imageBase + BigInt(ro), record + 32);
bytes.writeUInt32LE(2, ro);
bytes.writeUInt32LE(16, ro + 8);
bytes.writeBigUInt64LE(imageBase + BigInt(name), ro + 24);
}
bytes.write("KeptClass\0", 0x600);
if (!options.emptyMiddleClass) bytes.write("OtherClass\0", 0x620);
bytes.write("LaterClass\0", 0x640);
return bytes;
};
describe("Apple dispatch pointer fixup metadata", () => {
it.each([
{ name: "unsupported opcode", operand: [0xd0] },
{
name: "oversized addend whose tail resembles DO_BIND",
operand: [0x60, ...Array<number>(10).fill(0x80), 0x90, 0x00],
},
{
name: "a located bind with no selected symbol",
operand: [0x51, 0x70, 0x80, 0x1d, 0x90, 0],
missingTarget: true,
},
])(
"keeps decoded bindings when an independent stream has $name",
({ operand, missingTarget }) => {
const bytes = fixture();
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(200, 20);
bytes.writeUInt32LE(0x80000022, 184);
bytes.writeUInt32LE(48, 188);
const bindings = Buffer.from([
0x3e, // SET_DYLIB_SPECIAL_IMM flat lookup
0x40,
...Buffer.from("_OBJC_CLASS_$_NSObject\0"),
0x51, // SET_TYPE_IMM pointer
0x70,
0x88,
0x04,
0x90,
0x00,
]);
bindings.copy(bytes, 0xc00);
const invalid = Buffer.from([
...(missingTarget ? [] : bindings.subarray(0, -2)),
...operand,
]);
invalid.copy(bytes, 0xc80);
bytes.writeUInt32LE(0xc00, 200);
bytes.writeUInt32LE(bindings.length, 204);
bytes.writeUInt32LE(0xc80, 208);
bytes.writeUInt32LE(invalid.length, 212);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes[0]).toMatchObject({
name: "Fixture",
super_class: "NSObject",
});
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toMatchObject({
status: "partial",
examined: 2,
decoded: missingTarget ? 2 : 1,
reason: expect.stringContaining(
missingTarget
? "bind_target_unresolved at 0x100000e80: Legacy bind has no selected symbol"
: "bind_stream_decode_failed",
),
});
},
);
it("keeps absolute metadata pointers between declared chained fixups", () => {
const bytes = fixture();
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(168, 20);
bytes.writeUInt32LE(0x80000034, 184);
bytes.writeUInt32LE(16, 188);
bytes.writeUInt32LE(0xa00, 192);
bytes.writeUInt32LE(64, 196);
// Only the class-list pointer needs rebasing. All remaining metadata
// pointers carry their stored absolute values, outside the single chain.
bytes.writeBigUInt64LE(0x200n, 0x180);
bytes.writeUInt32LE(28, 0xa04);
bytes.writeUInt32LE(60, 0xa08);
bytes.writeUInt32LE(60, 0xa0c);
bytes.writeUInt32LE(1, 0xa14);
bytes.writeUInt32LE(1, 0xa1c);
bytes.writeUInt32LE(8, 0xa20);
bytes.writeUInt32LE(24, 0xa24);
bytes.writeUInt16LE(0x1000, 0xa28);
bytes.writeUInt16LE(6, 0xa2a);
bytes.writeUInt16LE(1, 0xa38);
bytes.writeUInt16LE(0x180, 0xa3a);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes[0]).toMatchObject({ name: "Fixture" });
expect(result.objc_dispatch_implementations[0]).toMatchObject({
selector: "performAction:",
implementation_address: "0x100000700",
});
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toMatchObject({ status: "complete", examined: 1, decoded: 1 });
});
});
describe("Apple dispatch binary metadata", () => {
it("retains structural Objective-C records when legacy rebase coverage is unknown", () => {
const bytes = fixture();
// Add LC_DYLD_INFO_ONLY with a nonempty rebase stream. Legacy rebase
// stream is malformed, so provenance is unknown while readable
// nonzero structural pointer words must remain useful.
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(200, 20);
bytes.writeUInt32LE(0x80000022, 184);
bytes.writeUInt32LE(48, 188);
bytes.writeUInt32LE(4000, 192);
bytes.writeUInt32LE(1, 196);
bytes.writeUInt8(0xf0, 4000);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes[0]?.name).toBe("Fixture");
expect(result.objc_classes[0]?.methods).toMatchObject([
{ selector: "performAction:" },
]);
expect(result.objc_classes[0]?.decode).toMatchObject({
status: "partial",
});
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({ status: "partial" });
expect(
result.coverage.find(({ facet }) => facet === "pointer_fixups"),
).toMatchObject({ status: "partial" });
});
it.each([false, true])(
"decodes stripped absolute/relative method lists (relative=%s) with exact offsets",
(relative) => {
const result = decodeAppleDispatchMetadata(
fixture(relative),
100,
provenance,
);
expect(result.objc_classes).toMatchObject([
{
name: "Fixture",
instance_size: 16,
location: { address: "0x100000200", file_offset: 512 },
},
{ name: "Fixture", is_meta_class: true },
]);
expect(result.objc_dispatch_implementations).toMatchObject([
{
selector: "performAction:",
implementation_address: "0x100000700",
location: { file_offset: 0x488 },
decode: { status: "decoded" },
},
]);
expect(result.objc_ivars).toMatchObject([
{
name: "state",
type_encoding: "i",
offset: 8,
alignment: 1,
location: { file_offset: 0x508 },
},
]);
expect(result.objc_classes[0]?.properties).toEqual([
{
name: "atomicValue",
type_encoding: "q",
attributes: [{ name: "T", value: "q" }],
atomicity: "atomic",
is_readonly: false,
getter: null,
setter: null,
},
{
name: "nonatomicValue",
type_encoding: "q",
attributes: [
{ name: "T", value: "q" },
{ name: "N", value: "" },
],
atomicity: "nonatomic",
is_readonly: false,
getter: null,
setter: null,
},
{
name: "unknownValue",
type_encoding: null,
attributes: [],
atomicity: null,
is_readonly: null,
getter: null,
setter: null,
},
]);
expect(result.objc_classes[0]).toMatchObject({
is_meta_class: false,
is_root_class: false,
ivar_count: 1,
});
expect(result.objc_classes[1]).toMatchObject({
is_meta_class: true,
is_root_class: false,
ivar_count: null,
});
expect(result.objc_classes[0]?.methods[0]).toMatchObject({
is_required: null,
is_optional: null,
});
expect(result.objc_protocols[0]).toMatchObject({
name: "FixtureProtocol",
methods: [
{
selector: "requiredAction:",
is_required: true,
is_optional: false,
},
],
optional_methods: [
{
selector: "optionalAction:",
is_required: false,
is_optional: true,
},
],
});
},
);
});
describe("Objective-C ivar alignment metadata", () => {
it("maps the ivar WORD_ALIGN sentinel to 8 and keeps other raw values unknown", () => {
const bytes = fixture();
bytes.writeUInt32LE(3, 0x504);
bytes.writeUInt32LE(3, 0x520);
// Second ivar: raw alignment 0xffffffff is objc4's WORD_ALIGN sentinel,
// which ivar_t::alignment() maps to 1 << WORD_SHIFT (8 on 64-bit).
bytes.writeBigUInt64LE(base + 0x6a0n, 0x528);
bytes.writeBigUInt64LE(base + 0x6c0n, 0x530);
bytes.writeBigUInt64LE(base + 0x6e0n, 0x538);
bytes.writeUInt32LE(0xffffffff, 0x540);
bytes.writeUInt32LE(8, 0x544);
bytes.writeUInt32LE(16, 0x6a0);
bytes.write("sentinel\0", 0x6c0);
bytes.write("q\0", 0x6e0);
// Third ivar: a non-sentinel out-of-range raw value stays unknown.
bytes.writeBigUInt64LE(base + 0x6a8n, 0x548);
bytes.writeBigUInt64LE(base + 0x6d0n, 0x550);
bytes.writeBigUInt64LE(base + 0x6e8n, 0x558);
bytes.writeUInt32LE(0xfffffffe, 0x560);
bytes.writeUInt32LE(8, 0x564);
bytes.writeUInt32LE(24, 0x6a8);
bytes.write("invalid\0", 0x6d0);
bytes.write("q\0", 0x6e8);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_ivars).toMatchObject([
{ name: "state", offset: 8, alignment: 8, decode: { status: "decoded" } },
{
name: "sentinel",
offset: 16,
size: 8,
alignment: 8,
decode: { status: "decoded" },
},
{
name: "invalid",
offset: 24,
size: 8,
alignment: null,
decode: { status: "decoded" },
},
]);
});
});
/**
* Fixture's class with three ivars as Swift emits them: `state` at a fixed
* offset, `tail` with a zero placeholder offset, and `registrar` whose type
* has no fixed layout (offset, size and alignment 1 stored as placeholders).
*/
const swiftLayoutFixture = (initializer: boolean) => {
const bytes = fixture();
// Root class and metaclass, so superclass bindings add no coverage reasons.
// 0x40 is objc4 RO_HAS_SWIFT_INITIALIZER on Fixture's class_ro_t.
bytes.writeUInt32LE(initializer ? 0x42 : 2, 0x300);
bytes.writeUInt32LE(3, 0x380);
bytes.writeUInt32LE(3, 0x504);
bytes.writeUInt32LE(3, 0x520);
bytes.writeUInt32LE(8, 0x524);
bytes.writeBigUInt64LE(base + 0x6a0n, 0x528);
bytes.writeBigUInt64LE(base + 0x6c0n, 0x530);
bytes.writeBigUInt64LE(base + 0x6e0n, 0x538);
bytes.writeUInt32LE(3, 0x540);
bytes.writeUInt32LE(8, 0x544);
bytes.write("tail\0", 0x6c0);
bytes.write("q\0", 0x6e0);
bytes.writeBigUInt64LE(base + 0x6a8n, 0x548);
bytes.writeBigUInt64LE(base + 0x6d0n, 0x550);
bytes.writeBigUInt64LE(base + 0x6e8n, 0x558);
bytes.write("registrar\0", 0x6d0);
bytes.write("\0", 0x6e8);
return decodeAppleDispatchMetadata(bytes, 100, provenance);
};
describe("Objective-C ivar layout assigned by a Swift metadata initializer", () => {
it("reports placeholder offsets and layouts as unknown when the class has a Swift initializer", () => {
const result = swiftLayoutFixture(true);
expect(
result.objc_ivars.map(
({ name, type_encoding, offset, size, alignment, decode }) => ({
name,
type_encoding,
offset,
size,
alignment,
decode,
}),
),
).toEqual([
{
name: "state",
type_encoding: "i",
offset: 8,
size: 8,
alignment: 8,
decode: { status: "decoded", reason: null },
},
{
name: "tail",
type_encoding: "q",
offset: null,
size: 8,
alignment: 8,
decode: { status: "partial", reason: "ivar_layout_assigned_at_load" },
},
{
name: "registrar",
type_encoding: null,
offset: null,
size: null,
alignment: null,
decode: { status: "partial", reason: "ivar_layout_assigned_at_load" },
},
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason:
"ivar Fixture.tail: ivar_layout_assigned_at_load; ivar Fixture.registrar: ivar_layout_assigned_at_load",
});
});
it("keeps stored zero offsets and sizes of a class without a Swift initializer", () => {
const result = swiftLayoutFixture(false);
expect(
result.objc_ivars.map(({ name, offset, size, alignment, decode }) => ({
name,
offset,
size,
alignment,
status: decode.status,
})),
).toEqual([
{ name: "state", offset: 8, size: 8, alignment: 8, status: "decoded" },
{ name: "tail", offset: 0, size: 8, alignment: 8, status: "decoded" },
{
name: "registrar",
offset: 0,
size: 0,
alignment: 1,
status: "decoded",
},
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({ status: "complete", reason: null });
});
});
describe("Apple dispatch coverage ownership", () => {
it("keeps unsupported pointers and record truncation explicit", () => {
const bytes = fixture();
bytes.writeBigUInt64LE(0xffffffffffffffffn, 0x498);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_dispatch_implementations[0]).toMatchObject({
implementation_address: null,
decode: { status: "partial" },
});
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("method Fixture instance performAction:"),
});
const truncated = decodeAppleDispatchMetadata(fixture(), 1, provenance);
expect(truncated.coverage[0]?.reason).toContain("max_records_reached");
expect(
truncated.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({ status: "partial", reason: "max_records_reached" });
});
it("keeps partial category methods in category coverage only", () => {
const baseline = decodeAppleDispatchMetadata(fixture(), 100, provenance);
const result = decodeAppleDispatchMetadata(
fixture(false, "partial-method"),
100,
provenance,
);
expect(result.objc_dispatch_implementations).toContainEqual(
expect.objectContaining({
category: "FixtureCategory",
decode: {
status: "partial",
reason: "implementation_pointer_unmapped_or_encoded",
},
}),
);
const baselineClassCoverage = baseline.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
const classCoverage = result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
expect(baselineClassCoverage).toBeDefined();
expect(classCoverage).toEqual(baselineClassCoverage);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("category method FixtureCategory"),
});
});
it("keeps a category whose class reference is unmapped", () => {
const result = decodeAppleDispatchMetadata(
fixture(false, "unmapped-class"),
100,
provenance,
);
expect(result.objc_categories).toMatchObject([
{
name: "FixtureCategory",
class_name: null,
class_source: "unresolved",
decode: { status: "partial", reason: "category_class_unresolved" },
},
]);
expect(result.objc_categories[0]?.instance_methods).toHaveLength(1);
expect(result.objc_dispatch_implementations).toContainEqual(
expect.objectContaining({
category: "FixtureCategory",
class_name: "(FixtureCategory)",
implementation_address: "0x100000700",
}),
);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"category_class_unresolved at 0x100000b48: Category FixtureCategory class reference 0x100005000",
),
});
});
it("keeps malformed category pointers out of class failure coverage", () => {
const baseline = decodeAppleDispatchMetadata(fixture(), 100, provenance);
const result = decodeAppleDispatchMetadata(
fixture(false, "unmapped-pointer"),
100,
provenance,
);
const baselineClassCoverage = baseline.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
const classCoverage = result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
expect(baselineClassCoverage).toBeDefined();
expect(classCoverage).toEqual(baselineClassCoverage);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("category_decode_failed"),
});
});
});
describe("Objective-C category class references without a class name", () => {
const categoryCoverage = (bytes: Buffer) => {
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_categories).toMatchObject([
{
name: "FixtureCategory",
class_name: null,
class_source: "unresolved",
decode: { status: "partial", reason: "category_class_unresolved" },
},
]);
return result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
);
};
it("names a class reference bound to a Swift class metadata symbol", () => {
// swiftc emits a category for @objc members of another module's Swift
// class and binds its class field to `_$s…CN`, not `_OBJC_CLASS_$_`.
const bytes = fixture(false, "unmapped-class");
bytes.writeBigUInt64LE(0n, 0xb48);
// LC_DYLD_INFO_ONLY after the segment command binds the class field.
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(280, 20);
bytes.writeUInt32LE(0x80000022, 264);
bytes.writeUInt32LE(48, 268);
const bindings = Buffer.from([
0x3e, // SET_DYLIB_SPECIAL_IMM flat lookup
0x40,
...Buffer.from("_$s4Main3FooCN\0"),
0x51, // SET_TYPE_IMM pointer
0x70,
0xc8,
0x16,
0x90,
0x00,
]);
bindings.copy(bytes, 0xc00);
bytes.writeUInt32LE(0xc00, 280);
bytes.writeUInt32LE(bindings.length, 284);
expect(categoryCoverage(bytes)).toMatchObject({
status: "partial",
reason: expect.stringMatching(
/category_class_unresolved.*0x100000b48.*FixtureCategory.*_\$s4Main3FooCN.*not read as an Objective-C class name/iu,
),
});
});
it("explains a null class reference", () => {
const bytes = fixture(false, "unmapped-class");
bytes.writeBigUInt64LE(0n, 0xb48);
expect(categoryCoverage(bytes)).toMatchObject({
status: "partial",
reason: expect.stringMatching(
/category_class_unresolved.*0x100000b48.*FixtureCategory.*class reference is null/i,
),
});
});
});
describe("Objective-C categories in __objc_catlist2", () => {
/** A category on the local Fixture class, listed in `section`. */
const listedCategory = (section: string) => {
const bytes = fixture(false, "unmapped-class");
bytes.writeBigUInt64LE(base + 0x200n, 0xb48);
bytes.fill(0, 184, 200);
bytes.write(section, 184);
return bytes;
};
const categoryCoverage = (result: {
coverage: readonly { facet: string }[];
}) =>
result.coverage.find(({ facet }) => facet === "objc_properties_categories");
it("decodes a category listed in __objc_catlist2 like one in __objc_catlist", () => {
const catlist = decodeAppleDispatchMetadata(
listedCategory("__objc_catlist"),
100,
provenance,
);
const result = decodeAppleDispatchMetadata(
listedCategory("__objc_catlist2"),
100,
provenance,
);
expect(catlist.objc_categories).toMatchObject([
{
name: "FixtureCategory",
class_name: "Fixture",
class_source: "local",
instance_methods: ["performAction:"],
decode: { status: "decoded", reason: null },
},
]);
expect(result.objc_categories).toEqual(catlist.objc_categories);
expect(result.objc_dispatch_implementations).toEqual(
catlist.objc_dispatch_implementations,
);
expect(categoryCoverage(result)).toEqual({
facet: "objc_properties_categories",
status: "complete",
reason: null,
examined: 1,
decoded: 1,
});
});
it("keeps a category on a Swift class stub without reading the stub as a class", () => {
const bytes = listedCategory("__objc_catlist2");
// A Swift class stub holds isa 1, then its metadata initializer.
bytes.writeBigUInt64LE(1n, 0xc80);
bytes.writeBigUInt64LE(base + 0x700n, 0xc88);
// Where a class_t keeps its data, the word after the stub can lead to an
// unrelated record; here it is Fixture's class_ro_t.
bytes.writeBigUInt64LE(base + 0x300n, 0xca0);
bytes.writeBigUInt64LE(base + 0xc80n, 0xb48);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_categories).toMatchObject([
{
name: "FixtureCategory",
class_name: null,
class_source: "unresolved",
instance_methods: ["performAction:"],
decode: { status: "partial", reason: "category_class_unresolved" },
},
]);
expect(result.objc_dispatch_implementations).toContainEqual(
expect.objectContaining({
category: "FixtureCategory",
class_name: "(FixtureCategory)",
implementation_address: "0x100000700",
}),
);
expect(categoryCoverage(result)).toMatchObject({
status: "partial",
reason:
"category_class_unresolved at 0x100000b48: Category FixtureCategory class reference 0x100000c80 is a Swift class stub, which is not read as an Objective-C class name",
examined: 1,
decoded: 0,
});
});
});
describe("Objective-C declaration-local record-budget coverage", () => {
it.each(["protocol", "class"] as const)(
"preserves the decoded $0 method at a sufficient budget",
(owner) => {
const result = decodeAppleDispatchMetadata(
objcRecordBudgetMacho(owner),
100,
provenance,
);
if (owner === "protocol")
expect(result.objc_protocol_records).toMatchObject([
{
name: "FixtureProtocol",
methods: [{ selector: "protocolMethod" }],
decode: { status: "decoded", reason: null },
},
]);
else
expect(result.objc_classes).toMatchObject([
{
name: "FixtureClass",
methods: [{ selector: "classMethod", method_type: "instance" }],
decode: { status: "decoded", reason: null },
},
]);
},
);
it("marks an omitted protocol method list partial while preserving known emptiness", () => {
const truncated = decodeAppleDispatchMetadata(
withProtocolListSection(fixture()),
1,
provenance,
);
expect(truncated.objc_protocol_records).toMatchObject([
{
name: "FixtureProtocol",
methods: [],
decode: { status: "partial", reason: "max_records_reached" },
},
]);
const emptyBytes = withProtocolListSection(fixture());
emptyBytes.writeBigUInt64LE(0n, 0x758);
emptyBytes.writeBigUInt64LE(0n, 0x768);
const empty = decodeAppleDispatchMetadata(emptyBytes, 1, provenance);
expect(empty.objc_protocol_records).toMatchObject([
{
name: "FixtureProtocol",
methods: [],
optional_methods: [],
decode: { status: "decoded", reason: null },
},
]);
});
it("marks omitted class methods, ivars, properties, and adopted protocols partial", () => {
const methodBytes = fixture();
methodBytes.writeUInt32LE(2, 0x300);
methodBytes.writeBigUInt64LE(0n, 0x330);
methodBytes.writeBigUInt64LE(0n, 0x340);
const methodLimited = decodeAppleDispatchMetadata(
methodBytes,
1,
provenance,
);
expect(methodLimited.objc_classes[0]).toMatchObject({
name: "Fixture",
methods: [],
decode: { status: "partial", reason: "max_records_reached" },
});
const ivarBytes = fixture();
ivarBytes.writeBigUInt64LE(0n, 0x320);
ivarBytes.writeBigUInt64LE(0n, 0x328);
ivarBytes.writeBigUInt64LE(0n, 0x340);
ivarBytes.writeUInt32LE(2, 0x300);
const ivarsLimited = decodeAppleDispatchMetadata(ivarBytes, 1, provenance);
expect(ivarsLimited.objc_classes[0]).toMatchObject({
name: "Fixture",
ivar_count: 1,
decode: { status: "partial", reason: "max_records_reached" },
});
expect(ivarsLimited.objc_ivars).toEqual([]);
const propertyBytes = fixture();
propertyBytes.writeBigUInt64LE(0n, 0x320);
propertyBytes.writeBigUInt64LE(0n, 0x328);
propertyBytes.writeBigUInt64LE(0n, 0x330);
propertyBytes.writeUInt32LE(2, 0x300);
const propertiesLimited = decodeAppleDispatchMetadata(
propertyBytes,
1,
provenance,
);
expect(propertiesLimited.objc_classes[0]).toMatchObject({
name: "Fixture",
properties: [],
decode: { status: "partial", reason: "max_records_reached" },
});
const adoptedBytes = fixture();
adoptedBytes.writeBigUInt64LE(0n, 0x320);
adoptedBytes.writeBigUInt64LE(0n, 0x330);
adoptedBytes.writeBigUInt64LE(0n, 0x340);
adoptedBytes.writeUInt32LE(2, 0x300);
const adoptedLimited = decodeAppleDispatchMetadata(
adoptedBytes,
1,
provenance,
);
expect(adoptedLimited.objc_classes[0]).toMatchObject({
name: "Fixture",
protocols: [],
decode: { status: "partial", reason: "max_records_reached" },
});
});
it("keeps genuinely empty class method lists decoded at the record limit", () => {
const bytes = fixture();
bytes.writeBigUInt64LE(0n, 0x320);
bytes.writeBigUInt64LE(0n, 0x328);
bytes.writeBigUInt64LE(0n, 0x330);
bytes.writeBigUInt64LE(0n, 0x340);
bytes.writeUInt32LE(2, 0x300);
const result = decodeAppleDispatchMetadata(bytes, 1, provenance);
expect(result.objc_classes[0]).toMatchObject({
name: "Fixture",
methods: [],
decode: { status: "decoded", reason: null },
});
});
});
describe("Objective-C category-local record-budget coverage", () => {
it.each(["instance", "class"] as const)(
"marks category %s methods partial only when a declared entry is omitted",
(methodType) => {
const bytes = fixture(false, "partial-method");
const listField = methodType === "instance" ? 0xb50 : 0xb58;
const methodList = bytes.readBigUInt64LE(0xb50);
bytes.writeBigUInt64LE(0n, 0xb50);
bytes.writeBigUInt64LE(methodList, listField);
bytes.writeUInt32LE(2, 0x300);
bytes.writeBigUInt64LE(0n, 0x320);
const truncated = decodeAppleDispatchMetadata(bytes, 11, provenance);
expect(truncated.objc_categories).toMatchObject([
{
name: "FixtureCategory",
[`${methodType}_methods`]: [],
decode: { status: "partial", reason: "max_records_reached" },
},
]);
bytes.writeBigUInt64LE(0n, listField);
const empty = decodeAppleDispatchMetadata(bytes, 11, provenance);
expect(empty.objc_categories).toMatchObject([
{
name: "FixtureCategory",
[`${methodType}_methods`]: [],
decode: { status: "decoded", reason: null },
},
]);
},
);
});
describe("malformed Objective-C property records", () => {
it.each(["class", "category"] as const)(
"retains the %s identity when its property-list pointer field is unmapped",
(owner) => {
const bytes = fixture(false, "partial-method");
if (owner === "class") {
bytes.writeBigUInt64LE(base + 0xfc0n, 0x220);
bytes.writeUInt32LE(2, 0xfc0);
bytes.writeUInt32LE(16, 0xfc8);
bytes.writeBigUInt64LE(base + 0x450n, 0xfd8);
} else {
bytes.writeBigUInt64LE(base + 0xfd8n, 0xb00);
bytes.writeBigUInt64LE(base + 0xbc0n, 0xfd8);
bytes.writeBigUInt64LE(base + 0x200n, 0xfe0);
}
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
if (owner === "class")
expect(result.objc_classes).toContainEqual(
expect.objectContaining({ name: "Fixture", is_meta_class: false }),
);
else
expect(result.objc_categories).toMatchObject([
{ name: "FixtureCategory", class_name: "Fixture", properties: [] },
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"property_decode_failed at 0x100001000",
),
});
},
);
it.each([
["an unmapped name", { secondNameOffset: 0x2000 }, "first", "0x100000518"],
["an empty name", { firstName: "" }, "second", "0x100000508"],
] as const)(
"retains the valid sibling of a property with %s",
(_, layout, kept, location) => {
const result = decodeAppleDispatchMetadata(
machoWithPropertyAttributes("Tq,N", layout),
100,
provenance,
);
expect(
result.objc_classes.map(({ name, properties }) => ({
name,
properties: properties.map((property) => property.name),
})),
).toEqual([{ name: "Fixture", properties: [kept] }]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining(
`property_decode_failed at ${location}: Fixture: property`,
),
});
},
);
});
describe("Objective-C malformed identity recovery", () => {
it.each(["class selector", "category name"] as const)(
"isolates an empty %s before result validation",
(malformed) => {
const bytes = fixture(false, "unmapped-class");
bytes.writeBigUInt64LE(base + 0xc00n, 0xb88);
bytes.write("categoryAction:\0", 0xc00);
bytes[malformed === "class selector" ? 0x460 : 0xbc0] = 0;
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
if (malformed === "class selector") {
expect(result.objc_categories).toMatchObject([
{ name: "FixtureCategory", instance_methods: ["categoryAction:"] },
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"0x100000180: Objective-C method has an empty selector",
),
});
} else {
expect(result.objc_categories).toEqual([]);
expect(result.objc_classes).toHaveLength(2);
expect(result.objc_classes[0]?.methods).toMatchObject([
{ selector: "performAction:" },
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("empty name"),
});
expect(result.objc_protocols).toMatchObject([
{ name: "FixtureProtocol" },
]);
}
},
);
it("keeps an unresolved superclass address when its class name is empty", () => {
const bytes = fixture();
bytes.writeBigUInt64LE(base + 0xc00n, 0x208);
bytes.writeBigUInt64LE(base + 0xc40n, 0xc20);
bytes.writeBigUInt64LE(base + 0xc80n, 0xc58);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes[0]).toMatchObject({
name: "Fixture",
super_class: null,
superclass_address: "0x100000c00",
});
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("Superclass pointer 0x100000c00"),
});
});
it("keeps a category whose local owner has an empty name", () => {
const bytes = fixture(false, "unmapped-class");
bytes.writeBigUInt64LE(base + 0xc00n, 0xb48);
bytes.writeBigUInt64LE(base + 0xc40n, 0xc20);
bytes.writeBigUInt64LE(base + 0xc80n, 0xc58);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes.map(({ name }) => name)).toEqual([
"Fixture",
"Fixture",
]);
expect(result.objc_categories).toMatchObject([
{
name: "FixtureCategory",
class_name: null,
class_source: "unresolved",
instance_methods: ["performAction:"],
decode: { status: "partial", reason: "category_class_unresolved" },
},
]);
expect(result.objc_dispatch_implementations).toContainEqual(
expect.objectContaining({
category: "FixtureCategory",
class_name: "(FixtureCategory)",
selector: "performAction:",
implementation_address: "0x100000700",
}),
);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("empty name"),
});
});
it.each([0x920, 0x940])(
"isolates an empty protocol selector at %i while keeping adopted declarations and classes",
(selector) => {
const bytes = fixture();
bytes[selector] = 0;
// Decode the independent adopted declaration before the malformed parent.
bytes.writeBigUInt64LE(base + 0xa00n, 0x750);
bytes.writeBigUInt64LE(1n, 0xa00);
bytes.writeBigUInt64LE(base + 0xa40n, 0xa08);
bytes.writeBigUInt64LE(base + 0xac0n, 0xa48);
bytes.writeUInt32LE(72, 0xa80);
bytes.write("AdoptedProtocol\0", 0xac0);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes.map(({ name }) => name)).toEqual([
"Fixture",
"Fixture",
]);
expect(result.objc_protocols.map(({ name }) => name)).toEqual([
"AdoptedProtocol",
"FixtureProtocol",
]);
expect(result.objc_protocol_records.map(({ name }) => name)).toEqual([
"AdoptedProtocol",
"FixtureProtocol",
]);
expect(result.objc_protocol_records[1]).toMatchObject({
adopted_protocols: ["AdoptedProtocol"],
methods: selector === 0x920 ? [] : [{ selector: "requiredAction:" }],
optional_methods:
selector === 0x940 ? [] : [{ selector: "optionalAction:" }],
decode: { status: "partial", reason: "protocol_method_selector_empty" },
});
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("empty selector"),
});
},
);
});
describe("malformed Apple dispatch metadata", () => {
it("retains valid class siblings when one class has an empty ivar name", () => {
const bytes = partialSiblingsFixture();
bytes.writeBigUInt64LE(base + 0x700n, 0x570);
bytes.writeUInt32LE(32, 0x700);
bytes.writeUInt32LE(1, 0x704);
bytes.writeBigUInt64LE(base + 0x800n, 0x708);
bytes.writeBigUInt64LE(base + 0x820n, 0x710);
bytes.writeBigUInt64LE(base + 0x840n, 0x718);
bytes.write("i\0", 0x840);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes.map(({ name }) => name)).toEqual([
"KeptClass",
"LaterClass",
]);
expect(result.objc_ivars).toEqual([]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("empty name"),
});
});
it("retains valid class siblings when one class has an empty name", () => {
const result = decodeAppleDispatchMetadata(
partialSiblingsFixture({ emptyMiddleClass: true }),
100,
provenance,
);
expect(result.objc_classes.map(({ name }) => name)).toEqual([
"KeptClass",
"LaterClass",
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({ status: "partial", examined: 3 });
});
it("retains valid Swift class vtable siblings when one descriptor has an empty class name", () => {
const bytes = Buffer.alloc(4096);
const base = 0x100000000n;
const u32 = (at: number, n: number) => bytes.writeUInt32LE(n, at);
const ptr = (at: number, n: number) =>
bytes.writeBigUInt64LE(base + BigInt(n), at);
const rel = (at: number, n: number) => bytes.writeInt32LE(n - at, at);
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);
ptr(56, 0);
bytes.writeBigUInt64LE(4096n, 64);
bytes.writeBigUInt64LE(4096n, 80);
u32(88, 5);
u32(92, 5);
u32(96, 1);
bytes.write("__swift5_types", 104);
bytes.write("__TEXT", 120);
ptr(136, 0x200);
bytes.writeBigUInt64LE(12n, 144);
u32(152, 0x200);
const entries: readonly (readonly [number, number, number, number])[] = [
[0x200, 0x300, 0x500, 0x800],
[0x204, 0x380, 0x520, 0x810],
[0x208, 0x400, 0x540, 0x820],
];
for (const [field, descriptor, name, implementation] of entries) {
rel(field, descriptor);
u32(descriptor, 0x80000010);
rel(descriptor + 8, name);
u32(descriptor + 28, 1);
u32(descriptor + 44, 0);
u32(descriptor + 48, 1);
u32(descriptor + 52, 0);
rel(descriptor + 56, implementation);
}
bytes.write("EarlierClass\0", 0x500);
bytes.write("LaterClass\0", 0x540);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_dispatch_slots.map(({ owner }) => owner)).toEqual([
"EarlierClass",
"LaterClass",
]);
expect(result.swift_decls.map(({ name }) => name)).toEqual([
"EarlierClass",
"LaterClass",
]);
const coverage = result.coverage.find(
({ facet }) => facet === "swift_class_vtable_descriptors",
);
expect(coverage).toMatchObject({
status: "partial",
examined: 2,
decoded: 2,
reason: expect.stringContaining("type descriptor name is empty"),
});
});
it("rejects malformed command and section boundaries", () => {
const bytes = fixture();
bytes.writeUInt32LE(7, 36);
expect(() => decodeAppleDispatchMetadata(bytes, 100, provenance)).toThrow(
malformedInput(
"macho",
"load command 0 at offset 0 has invalid cmdsize 7",
),
);
expect(() =>
decodeAppleDispatchMetadata(Buffer.alloc(10), 100, provenance),
).toThrow("Truncated");
});
});
/** Decode a universal image at the slice target admission selected. */
const decodeAdmitted = (
bytes: Buffer,
admitted: { readonly offset: number; readonly size: number },
architecture = "arm64",
) =>
decodeAppleDispatchMetadata(
bytes,
100,
provenance,
architecture,
undefined,
true,
admitted,
);
const dispatchFatOffset = 4096;
const wrapDispatchSlice = (wide: boolean, littleEndian = false) => {
const thin = fixture();
return {
bytes: Buffer.from(
fatImage([{ cpu: CPU.arm64, bytes: thin }], wide, littleEndian),
),
admitted: { offset: dispatchFatOffset, size: thin.length },
};
};
const wrapDispatchCapabilities = () => {
const slices = [0x81000002, 0x80000002].map((subtype) => {
const bytes = fixture();
bytes.writeUInt32LE(subtype, 8);
return { cpu: { type: CPU.arm64.type, subtype }, bytes };
});
const bytes = Buffer.from(fatImage(slices));
return { bytes, admitted: fatSliceRange(bytes, 1) };
};
describe("universal Apple dispatch metadata", () => {
it.each([
["big-endian FAT32", false, false],
["big-endian FAT64", true, false],
["byte-swapped FAT32", false, true],
["byte-swapped FAT64", true, true],
] as const)("decodes the selected %s slice", (_, wide, littleEndian) => {
// This row also guards against re-selecting a preferred subtype after admission.
const { bytes, admitted } =
wide || littleEndian
? wrapDispatchSlice(wide, littleEndian)
: wrapDispatchCapabilities();
const result = decodeAdmitted(bytes, admitted);
expect(result.objc_classes[0]).toMatchObject({
name: "Fixture",
location: {
address: "0x100000200",
file_offset: admitted.offset + 512,
},
});
expect(result.objc_dispatch_implementations[0]).toMatchObject({
implementation_address: "0x100000700",
location: { file_offset: admitted.offset + 0x488 },
});
});
});
describe("FAT64 dispatch slice validation", () => {
it("refuses a table that extends past the file as truncated", () => {
const { bytes, admitted } = wrapDispatchSlice(true);
// A FAT64 header cannot be a JVM class, so a table past the file's end
// is a cut-off universal file, measured against the file's size.
expect(() =>
decodeAppleDispatchMetadata(bytes.subarray(0, 32), 100, provenance),
).toThrow(
expect.objectContaining({
failure: expect.objectContaining({
kind: "truncated",
format: "macho",
extent: { availableBytes: 32, requiredBytes: 40 },
}),
}),
);
// Admitted selection reads the same container, so the cut-off file's
// own truncation wins over an admission mismatch.
expect(() => decodeAdmitted(bytes.subarray(0, 32), admitted)).toThrow(
expect.objectContaining({
failure: expect.objectContaining({
kind: "truncated",
extent: { availableBytes: 32, requiredBytes: 40 },
}),
}),
);
});
it.each([16, 24])(
"checks the full 64-bit slice extent at field %i",
(field) => {
const { bytes, admitted } = wrapDispatchSlice(true);
bytes.writeBigUInt64BE(0x100000000n, field);
// The declaration still names the admitted range in its other field.
const range =
field === 16
? { offset: 0x100000000, size: admitted.size }
: { offset: dispatchFatOffset, size: 0x100000000 };
expect(() => decodeAdmitted(bytes, range)).toThrow(
"FAT architecture 0 slice range extends beyond the file",
);
},
);
it("rejects an admitted range the FAT table declares twice", () => {
const { bytes, admitted } = wrapDispatchSlice(true);
bytes.writeUInt32BE(2, 4);
bytes.copy(bytes, 40, 8, 40);
expect(() => decodeAdmitted(bytes, admitted)).toThrow(
"Mach-O slices 0 and 1 overlap.",
);
});
it("refuses a universal image without the admitted slice", () => {
const { bytes } = wrapDispatchSlice(true);
expect(
refusalOf(() => decodeAppleDispatchMetadata(bytes, 100, provenance)),
).toEqual({
target_path: provenance.path,
refusal: "admitted_slice_mismatch",
reason: "Universal Mach-O metadata needs the admitted slice",
});
});
it("rejects an admitted slice of another architecture", () => {
const { bytes, admitted } = wrapDispatchSlice(true);
expect(
refusalOf(() => decodeAdmitted(bytes, admitted, "x86_64")),
).toMatchObject({
refusal: "admitted_slice_mismatch",
reason: "Admitted FAT slice does not match the requested architecture",
});
});
});
describe("byte-swapped universal Apple dispatch metadata", () => {
it("refuses a truncated byte-swapped FAT header", () => {
const { bytes } = wrapDispatchSlice(false, true);
expect(() =>
decodeAppleDispatchMetadata(bytes.subarray(0, 6), 100, provenance),
).toThrow(
expect.objectContaining({
failure: expect.objectContaining({
kind: "truncated",
format: "macho",
extent: { availableBytes: 6, requiredBytes: 8 },
}),
}),
);
});
it("reads the selected thin slice's CPU identity in its own byte order", () => {
const { bytes, admitted } = wrapDispatchSlice(false, true);
bytes.writeUInt32BE(0xfeedfacf, dispatchFatOffset);
bytes.writeUInt32BE(0x0100000c, dispatchFatOffset + 4);
bytes.writeUInt32BE(0, dispatchFatOffset + 8);
expect(() => decodeAdmitted(bytes, admitted)).toThrow(
"Unsupported big-endian Mach-O CPU type",
);
});
it("rejects a 32-bit slice payload inside a little-endian container", () => {
const { bytes, admitted } = wrapDispatchSlice(false, true);
bytes.writeUInt32LE(12, 8);
bytes.writeUInt32LE(0, 12);
bytes.writeUInt32LE(0xfeedface, dispatchFatOffset);
bytes.writeUInt32LE(12, dispatchFatOffset + 4);
bytes.writeUInt32LE(0, dispatchFatOffset + 8);
expect(() => decodeAdmitted(bytes, admitted, "arm")).toThrow(
"Unsupported 32-bit Mach-O metadata",
);
});
it("checks the full little-endian FAT64 slice extent", () => {
const { bytes, admitted } = wrapDispatchSlice(true, true);
bytes.writeBigUInt64LE(0x100000000n, 16);
expect(() =>
decodeAdmitted(bytes, { offset: 0x100000000, size: admitted.size }),
).toThrow("FAT architecture 0 slice range extends beyond the file");
});
});
const unmappedProtocolSectionBase = 0x100000000n;
const unmappedProtocolImage = (bad: "protocol" | "class" | "neither") => {
const bytes = Buffer.alloc(4096);
bytes.writeUInt32LE(0xfeedfacf, 0);
bytes.writeUInt32LE(0x0100000c, 4);
bytes.writeUInt32LE(2, 12);
bytes.writeUInt32LE(1, 16);
bytes.writeUInt32LE(232, 20);
bytes.writeUInt32LE(0x19, 32);
bytes.writeUInt32LE(232, 36);
bytes.write("__DATA", 40);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase, 56);
bytes.writeBigUInt64LE(4096n, 64);
bytes.writeBigUInt64LE(4096n, 80);
bytes.writeUInt32LE(5, 92);
bytes.writeUInt32LE(2, 96);
bytes.write("__objc_classlist", 104);
bytes.writeBigUInt64LE(
unmappedProtocolSectionBase + (bad === "class" ? 0x9000n : 0x200n),
136,
);
bytes.writeBigUInt64LE(8n, 144);
bytes.write("__objc_protolist", 184);
bytes.writeBigUInt64LE(
unmappedProtocolSectionBase + (bad === "protocol" ? 0x9000n : 0x300n),
216,
);
bytes.writeBigUInt64LE(8n, 224);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x400n, 0x200);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x500n, 0x420);
bytes.writeUInt32LE(2, 0x500);
bytes.writeUInt32LE(16, 0x508);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x600n, 0x518);
bytes.write("RetainedClass\0", 0x600);
return bytes;
};
const unmappedProtocolClassCoverage = (result: {
coverage: { facet: string; status: string; reason: string | null }[];
}) =>
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
describe("Apple dispatch unmapped protocol-list slot", () => {
it("returns the class when every list slot is mapped", () => {
const result = decodeAppleDispatchMetadata(
unmappedProtocolImage("neither"),
100,
provenance,
);
expect(result.objc_classes).toMatchObject([{ name: "RetainedClass" }]);
expect(unmappedProtocolClassCoverage(result)).toMatchObject({
status: "complete",
});
});
it("records partial coverage when the class-list slot is unmapped", () => {
const result = decodeAppleDispatchMetadata(
unmappedProtocolImage("class"),
100,
provenance,
);
expect(unmappedProtocolClassCoverage(result)).toMatchObject({
status: "partial",
reason: expect.stringContaining("0x100009000"),
});
});
it("retains the class and partial coverage when the protocol-list slot is unmapped", () => {
const result = decodeAppleDispatchMetadata(
unmappedProtocolImage("protocol"),
100,
provenance,
);
expect(result.objc_classes).toMatchObject([{ name: "RetainedClass" }]);
expect(unmappedProtocolClassCoverage(result)).toMatchObject({
status: "partial",
reason: expect.stringContaining("0x100009000"),
});
});
});
describe("Apple dispatch list scan budget", () => {
it("bounds failed protocol-list slots by the record budget", () => {
// The section size is file-declared, so a crafted image can claim an
// arbitrarily large unmapped protocol list. Failed slots must spend the
// record budget like decoded ones, otherwise the loop runs unbounded.
const bytes = unmappedProtocolImage("protocol");
bytes.writeBigUInt64LE(80000n, 224);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
const coverage = unmappedProtocolClassCoverage(result);
expect(coverage).toMatchObject({ status: "partial" });
expect(coverage?.reason).toContain("max_records_reached");
const failures =
coverage?.reason?.match(/Unmapped or ambiguous metadata pointer/g) ?? [];
expect(failures.length).toBeLessThanOrEqual(100);
});
it("keeps independent facets complete when only zero-pointer list scanning is capped", () => {
const bytes = unmappedProtocolImage("neither");
bytes.writeBigUInt64LE(0n, 144);
bytes.writeBigUInt64LE(16n, 224);
const result = decodeAppleDispatchMetadata(bytes, 1, provenance);
expect(unmappedProtocolClassCoverage(result)).toMatchObject({
status: "partial",
reason: expect.stringContaining("max_records_reached"),
});
for (const facet of [
"objc_properties_categories",
"binary_relative_pointers",
])
expect(
result.coverage.find((item) => item.facet === facet),
).toMatchObject({
status: "complete",
reason: null,
});
});
it("marks class-dependent coverage partial when zero slots hide a later class", () => {
const bytes = unmappedProtocolImage("neither");
bytes.writeBigUInt64LE(0n, 224);
bytes.writeBigUInt64LE(16n, 144);
bytes.writeBigUInt64LE(0n, 0x200);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x400n, 0x208);
const result = decodeAppleDispatchMetadata(bytes, 1, provenance);
expect(result.objc_classes).toEqual([]);
for (const facet of [
"objc_class_method_ivar_metadata",
"objc_properties_categories",
"binary_relative_pointers",
])
expect(
result.coverage.find((item) => item.facet === facet),
).toMatchObject({
status: "partial",
reason: expect.stringContaining("max_records_reached"),
});
for (const facet of [
"swift_class_vtable_descriptors",
"swift_conformances_static_witness_slots",
])
expect(
result.coverage.find((item) => item.facet === facet),
).toMatchObject({ status: "complete" });
});
it("bounds failed class-list slots by the record budget", () => {
// Same file-declared-size hazard as the protocol list: a crafted image
// can declare an arbitrarily large unmapped class list. Failed class
// slots must spend the record budget like decoded ones, otherwise the
// loop runs unbounded (each failed read produced an unbounded failure
// string with no budget spend).
const bytes = unmappedProtocolImage("class");
bytes.writeBigUInt64LE(80000n, 144);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
const coverage = unmappedProtocolClassCoverage(result);
expect(coverage).toMatchObject({ status: "partial" });
expect(coverage?.reason).toContain("max_records_reached");
const failures =
coverage?.reason?.match(/Unmapped or ambiguous metadata pointer/g) ?? [];
expect(failures.length).toBeLessThanOrEqual(100);
});
it("reports the real failure for a mapped-but-malformed class at the budget boundary", () => {
// The class-list slot itself is mapped, so readClass admits the record
// budget and only then throws on the unmapped class_ro pointer. The
// failure must be recorded as-is: it already spent one budget unit, so
// admitting again would break before the reason is appended and report
// only max_records_reached.
const bytes = unmappedProtocolImage("neither");
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x700n, 0x200);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x9000n, 0x720);
const result = decodeAppleDispatchMetadata(bytes, 1, provenance);
const coverage = unmappedProtocolClassCoverage(result);
expect(coverage).toMatchObject({ status: "partial" });
expect(coverage?.reason).toContain(
"Unmapped or ambiguous metadata pointer 0x100009018",
);
expect(coverage?.reason).not.toContain("max_records_reached");
});
it("does not skip a valid class after a mapped-but-malformed class", () => {
// With two slots and a budget of two, the corrupt first slot must spend
// exactly one unit: admitting twice would exhaust the budget and skip
// the valid class behind it.
const bytes = unmappedProtocolImage("neither");
bytes.writeBigUInt64LE(16n, 144);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x700n, 0x200);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x9000n, 0x720);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x400n, 0x208);
const result = decodeAppleDispatchMetadata(bytes, 2, provenance);
expect(result.objc_classes).toMatchObject([{ name: "RetainedClass" }]);
expect(unmappedProtocolClassCoverage(result)?.reason).toContain(
"Unmapped or ambiguous metadata pointer 0x100009018",
);
});
it("reports the real failure for a mapped-but-truncated protocol slot", () => {
// The protocol slot is mapped, so protocolReader.record admits the
// budget itself before throwing on the truncated declaration. The loop
// must not admit a second time; the recorded reason stays the
// declaration failure, not max_records_reached.
const bytes = unmappedProtocolImage("neither");
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x700n, 0x300);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
const coverage = unmappedProtocolClassCoverage(result);
expect(coverage).toMatchObject({ status: "partial" });
expect(coverage?.reason).toContain(
"Truncated Objective-C protocol declaration",
);
expect(coverage?.reason).not.toContain("max_records_reached");
});
it.each([
["RetainedProtocol", ["RetainedProtocol"], "complete"],
["", [], "partial"],
])(
"keeps the class when the protocol name is %j",
(protocolName, protocols, status) => {
const bytes = unmappedProtocolImage("neither");
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x700n, 0x300);
bytes.writeBigUInt64LE(unmappedProtocolSectionBase + 0x800n, 0x708);
bytes.writeUInt32LE(72, 0x740);
bytes.write(`${protocolName}\0`, 0x800);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes).toMatchObject([{ name: "RetainedClass" }]);
expect(result.objc_protocols.map(({ name }) => name)).toEqual(protocols);
const coverage = unmappedProtocolClassCoverage(result);
expect(coverage).toMatchObject({ status });
if (status === "partial")
expect(coverage?.reason).toBe(
"Protocol 0x100000700: Objective-C protocol has an empty name",
);
},
);
it("keeps a protocol adopted only by an empty-named protocol", () => {
const bytes = unmappedProtocolImage("neither");
const at = (offset: bigint) => unmappedProtocolSectionBase + offset;
bytes.writeBigUInt64LE(at(0x700n), 0x300);
bytes.writeBigUInt64LE(at(0x800n), 0x708); // empty parent name
bytes.writeBigUInt64LE(at(0x900n), 0x710); // adopted protocol list
bytes.writeUInt32LE(72, 0x740);
bytes.writeBigUInt64LE(1n, 0x900);
bytes.writeBigUInt64LE(at(0xa00n), 0x908);
bytes.writeBigUInt64LE(at(0xb00n), 0xa08);
bytes.writeUInt32LE(72, 0xa40);
bytes.write("ChildProtocol\0", 0xb00);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes).toMatchObject([{ name: "RetainedClass" }]);
expect(result.objc_protocols.map(({ name }) => name)).toEqual([
"ChildProtocol",
]);
expect(unmappedProtocolClassCoverage(result)).toMatchObject({
status: "partial",
reason: "Protocol 0x100000700: Objective-C protocol has an empty name",
});
});
});
describe("malformed Objective-C protocol method lists", () => {
it("reports an empty protocol method selector without discarding the protocol or its other methods", () => {
const bytes = fixture();
bytes.writeUInt32LE(2, 0x804);
// The first required method names an empty string; the second is valid.
bytes.writeBigUInt64LE(base + 0x930n, 0x808);
bytes.writeBigUInt64LE(base + 0x920n, 0x820);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_protocols).toMatchObject([
{
name: "FixtureProtocol",
methods: [{ selector: "requiredAction:", is_required: true }],
optional_methods: [{ selector: "optionalAction:", is_optional: true }],
},
]);
expect(result.objc_protocol_records).toMatchObject([
{
name: "FixtureProtocol",
methods: [{ selector: "requiredAction:" }],
decode: { status: "partial", reason: "protocol_method_selector_empty" },
},
]);
expect(result.objc_classes.map(({ name }) => name)).toEqual([
"Fixture",
"Fixture",
]);
expect(result.objc_dispatch_implementations).toMatchObject([
{ selector: "performAction:" },
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"Protocol 0x100000740: Objective-C protocol FixtureProtocol required instance method 0 at 0x100000808 has an empty selector",
),
});
});
});
it("decodes protocol instance properties through the same property-list owner as classes", () => {
const bytes = fixture();
bytes.writeBigUInt64LE(base + 0x600n, 0x778);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_protocols[0]?.properties).toEqual(
result.objc_classes[0]?.properties,
);
expect(result.objc_protocols[0]?.properties).toHaveLength(3);
expect(result.objc_protocol_records[0]?.decode).toEqual({
status: "decoded",
reason: null,
});
});
it("retains protocol methods when its instance-property list is unreadable", () => {
const bytes = fixture();
bytes.writeBigUInt64LE(base + 0x5000n, 0x778);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_protocols[0]).toMatchObject({
name: "FixtureProtocol",
methods: [{ selector: "requiredAction:" }],
properties: [],
});
expect(result.objc_protocol_records[0]?.decode.status).toBe("partial");
expect(
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
)?.status,
).toBe("partial");
});
it("retains conformance facts beside an empty Swift protocol name", () => {
const bytes = swiftConformanceTypeReferenceImage(2);
bytes[0xe50] = 0;
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances[0]).toMatchObject({
type_name: "NSObject",
protocol_name: null,
decode: { status: "partial" },
});
expect(result.objc_classes).not.toHaveLength(0);
});
it("retains the enclosing Swift type and module in a conformance owner", () => {
const bytes = swiftBoundWitnessSlotImage();
bytes.writeInt32LE(0xc20 - 0xc04, 0xc04);
bytes.writeUInt32LE(17, 0xc20);
bytes.writeInt32LE(0xc40 - 0xc24, 0xc24);
bytes.writeInt32LE(0xea0 - 0xc28, 0xc28);
bytes.write("Outer\0", 0xea0);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances[0]).toMatchObject({
type_name: "Outer.Widget",
module: "FixtureModule",
decode: { status: "decoded" },
});
expect(result.swift_dispatch_slots[0]?.owner).toBe("Outer.Widget: Equatable");
});
it.each([false, true])(
"preserves a nested protocol identity and reports unread parent context (%s)",
(unreadParent) => {
const bytes = swiftBoundWitnessSlotImage();
// This identity regression uses a local executable witness, not an import.
bytes.writeUInt32LE(0, 280);
bytes.writeUInt32LE(0, 284);
bytes.writeBigUInt64LE(base + 0xb00n, 0xe08);
bytes.writeInt32LE(0xc20 - 0xd04, 0xd04);
bytes.writeUInt32LE(17, 0xc20);
bytes.writeInt32LE((unreadParent ? 0x5000 : 0xc40) - 0xc24, 0xc24);
bytes.writeInt32LE(0xea0 - 0xc28, 0xc28);
bytes.write("Outer\0", 0xea0);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.swift_conformances[0]).toMatchObject({
type_name: "Widget",
protocol_name: unreadParent ? "Equatable" : "Outer.Equatable",
module: "FixtureModule",
decode: { status: unreadParent ? "partial" : "decoded" },
});
expect(result.swift_dispatch_slots[0]).toMatchObject({
owner: unreadParent ? "Widget: Equatable" : "Widget: Outer.Equatable",
implementation_address: "0x100000b00",
decode: { status: "decoded" },
});
expect(
result.coverage.find(
({ facet }) => facet === "swift_conformances_static_witness_slots",
)?.status,
).toBe(unreadParent ? "partial" : "complete");
},
);
describe("Objective-C adopted protocol-list count limit", () => {
// Root class and metaclass that adopt the fixture protocol through the
// class_ro_t base protocol list at 0x700.
const rootClass = (protocolCount: bigint, category?: "partial-method") => {
const bytes = fixture(false, category);
bytes.writeUInt32LE(2, 12);
bytes.writeUInt32LE(5, 88);
bytes.writeUInt32LE(2, 0x300);
bytes.writeUInt32LE(3, 0x380);
bytes.writeBigUInt64LE(protocolCount, 0x700);
return bytes;
};
const classCoverage = (
result: ReturnType<typeof decodeAppleDispatchMetadata>,
) =>
result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
);
it("retains the class and metaclass rows when the list exceeds its count limit", () => {
const result = decodeAppleDispatchMetadata(
rootClass(20001n),
100,
provenance,
);
expect(
result.objc_classes.map(({ name, is_meta_class, protocols, decode }) => ({
name,
is_meta_class,
protocols,
decode,
})),
).toEqual([
{
name: "Fixture",
is_meta_class: false,
protocols: [],
decode: { status: "partial", reason: "protocol_list_unreadable" },
},
// The metaclass has no adopted-protocol list of its own.
{
name: "Fixture",
is_meta_class: true,
protocols: [],
decode: { status: "decoded", reason: null },
},
]);
expect(result.objc_classes[0]?.properties).toHaveLength(3);
expect(result.objc_ivars).toHaveLength(1);
expect(result.objc_dispatch_implementations).toMatchObject([
{ class_name: "Fixture", selector: "performAction:" },
]);
expect(classCoverage(result)).toMatchObject({
status: "partial",
// The class row is retained as partial, so it is examined but not
// counted as fully decoded; the metaclass is fully decoded.
examined: 2,
decoded: 1,
});
});
it("retains the readable protocol prefix when a later list slot is unmapped", () => {
const bytes = rootClass(2n);
bytes.writeBigUInt64LE(base + 0x5000n, 0x710);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_classes).toMatchObject([
{
name: "Fixture",
protocols: ["FixtureProtocol"],
decode: { status: "partial", reason: "protocol_list_unreadable" },
},
{ name: "Fixture", is_meta_class: true },
]);
expect(result.objc_protocol_records).toMatchObject([
{ name: "FixtureProtocol", decode: { status: "decoded" } },
]);
});
it("retains a category's own methods and properties after a protocol-list refusal", () => {
const bytes = rootClass(0n, "partial-method");
bytes.writeBigUInt64LE(base + 0x700n, 0xb98);
bytes.writeBigUInt64LE(base + 0x600n, 0xb68);
bytes.writeBigUInt64LE(base + 0xa00n, 0xb60);
bytes.writeBigUInt64LE(20001n, 0xa00);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_categories).toMatchObject([
{
name: "FixtureCategory",
class_name: "Fixture",
instance_methods: ["performAction:"],
protocols: [],
decode: { status: "partial", reason: "protocol_list_unreadable" },
},
]);
expect(result.objc_categories[0]?.properties).toHaveLength(3);
expect(classCoverage(result)?.status).toBe("complete");
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({ status: "partial" });
});
it("retains an adopting protocol's own method declarations after a list refusal", () => {
const bytes = rootClass(1n);
bytes.writeBigUInt64LE(base + 0xa00n, 0x750);
bytes.writeBigUInt64LE(20001n, 0xa00);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_protocol_records).toMatchObject([
{
name: "FixtureProtocol",
adopted_protocols: [],
methods: [{ selector: "requiredAction:" }],
optional_methods: [{ selector: "optionalAction:" }],
decode: { status: "partial", reason: "protocol_list_unreadable" },
},
]);
expect(result.objc_protocols).toMatchObject([
{ name: "FixtureProtocol", methods: [{ selector: "requiredAction:" }] },
]);
expect(result.objc_classes).toHaveLength(2);
expect(classCoverage(result)?.status).toBe("partial");
});
it.each([0n, 1n])(
"keeps complete class coverage for an in-limit count of %s",
(count) => {
const bytes = rootClass(count);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
const reason = classCoverage(result)?.reason ?? "";
expect(reason).not.toContain("Protocol list of Fixture");
expect(result.objc_classes).toHaveLength(2);
for (const row of result.objc_classes)
expect(row.decode?.reason ?? "").not.toContain(
"protocol_list_unreadable",
);
expect(classCoverage(result)?.status).toBe("complete");
},
);
});
describe("Swift type record sections", () => {
it("lists a noncopyable type recorded in __swift5_types2 beside __swift5_types", () => {
const bytes = Buffer.alloc(4096);
const u32 = (at: number, n: number) => bytes.writeUInt32LE(n, at);
const rel = (at: number, n: number) => bytes.writeInt32LE(n - at, at);
u32(0, 0xfeedfacf);
u32(4, 0x0100000c);
u32(12, 2);
u32(16, 1);
u32(20, 232);
u32(32, 0x19);
u32(36, 232);
bytes.write("__TEXT", 40);
bytes.writeBigUInt64LE(base, 56);
bytes.writeBigUInt64LE(4096n, 64);
bytes.writeBigUInt64LE(4096n, 80);
u32(88, 5);
u32(92, 5);
u32(96, 2);
const records = [
{ section: "__swift5_types", record: 0x200, descriptor: 0x300 },
{ section: "__swift5_types2", record: 0x210, descriptor: 0x380 },
];
for (const [index, { section, record, descriptor }] of records.entries()) {
const command = 104 + index * 80;
bytes.write(section, command);
bytes.write("__TEXT", command + 16);
bytes.writeBigUInt64LE(base + BigInt(record), command + 32);
bytes.writeBigUInt64LE(4n, command + 40);
u32(command + 48, record);
rel(record, descriptor);
u32(descriptor, 0x11);
rel(descriptor + 4, 0x400);
rel(descriptor + 8, 0x500 + index * 0x20);
}
rel(0x408, 0x540);
bytes.write("Plain\0", 0x500);
bytes.write("Owned\0", 0x520);
bytes.write("Fixture\0", 0x540);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(
result.swift_decls.map(
({ kind, qualified_name, module, decode, evidence }) => ({
kind,
qualified_name,
module,
decode,
evidence: evidence.map(({ description }) => description),
}),
),
).toEqual([
{
kind: "struct",
qualified_name: "Plain",
module: "Fixture",
decode: { status: "decoded", reason: null },
evidence: [
"Swift __swift5_types record of the nominal type descriptor at location",
],
},
{
kind: "struct",
qualified_name: "Owned",
module: "Fixture",
decode: { status: "decoded", reason: null },
evidence: [
"Swift __swift5_types2 record of the nominal type descriptor at location",
],
},
]);
expect(
result.coverage.find(({ facet }) => facet === "swift_declarations"),
).toMatchObject({ status: "complete", examined: 2, decoded: 2 });
});
});
/** A fully decoded category beside an image info; `_classProperties` is at 0xb70. */
const categoryImage = (flags: number, classProperties: number): Buffer => {
const bytes = fixture(false, "partial-method");
bytes.writeBigUInt64LE(base + 0x700n, 0xb98);
bytes.writeUInt32LE(312, 20);
bytes.writeUInt32LE(312, 36);
bytes.writeUInt32LE(3, 96);
bytes.write("__objc_imageinfo", 264);
bytes.write("__DATA", 280);
bytes.writeBigUInt64LE(base + 0xc00n, 296);
bytes.writeBigUInt64LE(8n, 304);
bytes.writeUInt32LE(0xc00, 312);
bytes.writeUInt32LE(flags, 0xc04);
if (classProperties !== 0)
bytes.writeBigUInt64LE(base + BigInt(classProperties), 0xb70);
return bytes;
};
const categoryFacts = (bytes: Buffer) => {
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
return {
decode: result.objc_categories.map(({ decode }) => decode),
coverage: result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
};
};
describe("Objective-C category class properties", () => {
it("marks a category partial when its declared class property list is not decoded", () => {
const { decode, coverage } = categoryFacts(categoryImage(0x40, 0x600));
expect(decode).toEqual([
{ status: "partial", reason: "category_class_properties_not_decoded" },
]);
expect(coverage).toMatchObject({
status: "partial",
reason:
"category_class_properties_not_decoded at 0x100000b70: Category FixtureCategory class property list is not decoded",
examined: 1,
decoded: 0,
});
});
it.each([
["has no class property list", 0x40, 0],
["does not declare the field", 0, 0x600],
])("keeps a category decoded when the image %s", (_, flags, list) => {
const { decode, coverage } = categoryFacts(categoryImage(flags, list));
expect(decode).toEqual([{ status: "decoded", reason: null }]);
expect(coverage).toMatchObject({ status: "complete", decoded: 1 });
});
it.each([
[
"class property field is unmapped",
(bytes: Buffer) => {
// End the record at the segment boundary, so its last field lies past it.
bytes.copy(bytes, 0xfd0, 0xb40, 0xb70);
bytes.writeBigUInt64LE(base + 0xfd0n, 0xb00);
},
"0x100001000",
],
[
"image info is unmapped",
(bytes: Buffer) => bytes.writeBigUInt64LE(base + 0x2000n, 296),
"0x100002004",
],
[
"image info is too short to hold its flags",
(bytes: Buffer) => bytes.writeBigUInt64LE(4n, 304),
"0x100000c00",
],
])("retains a category whose %s", (_, damage, field) => {
const bytes = categoryImage(0x40, 0);
damage(bytes);
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
expect(result.objc_categories).toMatchObject([
{
name: "FixtureCategory",
class_name: "Fixture",
instance_methods: [expect.any(String)],
decode: {
status: "partial",
reason: "category_class_properties_unreadable",
},
},
]);
expect(
result.coverage.find(
({ facet }) => facet === "objc_properties_categories",
),
).toMatchObject({
status: "partial",
reason: expect.stringContaining(
`category_class_properties_unreadable at ${field}: Category FixtureCategory class property list: `,
),
examined: 1,
decoded: 0,
});
});
});
describe("Objective-C category class property applicability", () => {
/** Move the class list pointer out of the header so load commands can grow. */
const freeLoadCommandSpace = (bytes: Buffer): void => {
bytes.writeBigUInt64LE(bytes.readBigUInt64LE(0x180), 0xe00);
bytes.writeBigUInt64LE(0n, 0x180);
bytes.writeBigUInt64LE(base + 0xe00n, 136);
bytes.writeUInt32LE(0xe00, 152);
};
/** Append LC_DYLD_INFO_ONLY; its rebase and bind streams are at 352 and 360. */
const withLegacyFixups = (bytes: Buffer): Buffer => {
freeLoadCommandSpace(bytes);
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(360, 20);
bytes.writeUInt32LE(0x80000022, 344);
bytes.writeUInt32LE(48, 348);
return bytes;
};
it("reports a class property list bound to another image as not decoded", () => {
const bytes = withLegacyFixups(categoryImage(0x40, 0));
const bindings = Buffer.from([
0x3e, // SET_DYLIB_SPECIAL_IMM flat lookup
0x40,
...Buffer.from("_external_list\0"),
0x51, // SET_TYPE_IMM pointer
0x70, // SET_SEGMENT_AND_OFFSET_ULEB: segment 0, offset 0xb70
0xf0,
0x16,
0x90,
0x00,
]);
bindings.copy(bytes, 0xf00);
bytes.writeUInt32LE(0xf00, 360);
bytes.writeUInt32LE(bindings.length, 364);
const { decode, coverage } = categoryFacts(bytes);
expect(decode).toEqual([
{ status: "partial", reason: "category_class_properties_not_decoded" },
]);
expect(coverage).toMatchObject({
status: "partial",
reason:
"category_class_properties_not_decoded at 0x100000b70: Category FixtureCategory class property list is bound to _external_list and is not decoded",
examined: 1,
decoded: 0,
});
});
it("does not read a zero class property field as null when its fixups are unknown", () => {
const bytes = withLegacyFixups(categoryImage(0x40, 0));
// An undecodable rebase stream leaves every raw pointer's fixup unknown.
bytes.writeUInt32LE(0xf80, 352);
bytes.writeUInt32LE(1, 356);
bytes.writeUInt8(0xf0, 0xf80);
const { decode, coverage } = categoryFacts(bytes);
expect(decode).toEqual([
{ status: "partial", reason: "category_class_properties_unreadable" },
]);
expect(coverage).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"category_class_properties_unreadable at 0x100000b70: Category FixtureCategory class property list: LC_DYLD_INFO pointer-fixup applicability was not completely decoded",
),
examined: 1,
decoded: 0,
});
});
it("reads the field when one image info declares it beside one too short to hold flags", () => {
const bytes = categoryImage(0x40, 0x600);
freeLoadCommandSpace(bytes);
bytes.writeUInt32LE(392, 20);
bytes.writeUInt32LE(392, 36);
bytes.writeUInt32LE(4, 96);
bytes.write("__objc_imageinfo", 344);
bytes.write("__DATA", 360);
bytes.writeBigUInt64LE(base + 0xc40n, 376);
bytes.writeBigUInt64LE(4n, 384);
bytes.writeUInt32LE(0xc40, 392);
const { decode, coverage } = categoryFacts(bytes);
expect(decode).toEqual([
{ status: "partial", reason: "category_class_properties_not_decoded" },
]);
expect(coverage).toMatchObject({
reason: expect.stringContaining(
"category_class_properties_not_decoded at 0x100000b70",
),
});
});
});
/**
* Minimal Mach-O with one `__objc_protolist` entry pointing at a `protocol_t`
* at 0x740 (`instanceProperties` at 0x778, `size` at 0x780, `_classProperties` at 0x798).
*/
const protocolClassPropertiesImage = (
protocolSize: number,
classProperties: number,
): Buffer => {
const bytes = Buffer.alloc(4096);
const u32 = (offset: number, value: number) =>
bytes.writeUInt32LE(value, offset);
const ptr = (offset: number, target: number) =>
bytes.writeBigUInt64LE(base + BigInt(target), offset);
u32(0, 0xfeedfacf);
u32(4, 0x0100000c);
u32(16, 1);
u32(20, 152);
u32(32, 0x19);
u32(36, 152);
bytes.write("__DATA", 40);
ptr(56, 0);
bytes.writeBigUInt64LE(4096n, 64);
bytes.writeBigUInt64LE(4096n, 80);
u32(92, 5);
u32(96, 1);
bytes.write("__objc_protolist", 104);
bytes.write("__DATA", 120);
ptr(136, 0x708);
bytes.writeBigUInt64LE(8n, 144);
u32(152, 0x708);
ptr(0x708, 0x740);
ptr(0x748, 0x900);
ptr(0x758, 0x800);
ptr(0x778, 0x600);
u32(0x780, protocolSize);
if (classProperties !== 0) ptr(0x798, classProperties);
u32(0x800, 24);
u32(0x804, 1);
ptr(0x808, 0x920);
u32(0x600, 16);
u32(0x604, 1);
ptr(0x608, 0x640);
ptr(0x610, 0x650);
bytes.write("title\0", 0x640);
bytes.write("Tq,N\0", 0x650);
bytes.write("FixtureProtocol\0", 0x900);
bytes.write("requiredAction:\0", 0x920);
return bytes;
};
describe("Objective-C protocol class properties", () => {
/** Append LC_DYLD_INFO_ONLY at 184; rebase stream is at 192, bind stream is at 200. */
const withLegacyFixups = (bytes: Buffer): Buffer => {
bytes.writeUInt32LE(2, 16);
bytes.writeUInt32LE(200, 20);
bytes.writeUInt32LE(0x80000022, 184);
bytes.writeUInt32LE(48, 188);
return bytes;
};
/** Bind segment 0 offset 0x798 (`_classProperties`) to an external symbol. */
const bindClassProperties = (bytes: Buffer, symbol: string): void => {
const bindings = Buffer.from([
0x3e, // SET_DYLIB_SPECIAL_IMM flat lookup
0x40,
...Buffer.from(`${symbol}\0`),
0x51, // SET_TYPE_IMM pointer
0x70, // SET_SEGMENT_AND_OFFSET_ULEB: segment 0, offset 0x798
0x98,
0x0f,
0x90, // DO_BIND
0x00,
]);
bindings.copy(bytes, 0xf00);
bytes.writeUInt32LE(0xf00, 200);
bytes.writeUInt32LE(bindings.length, 204);
};
/** Rebase segment 0 offset 0x798 (`_classProperties`) as a 64-bit pointer. */
const rebaseClassProperties = (bytes: Buffer): void => {
const rebases = Buffer.from([
0x11, // REBASE_OPCODE_SET_TYPE_IMM pointer
0x20, // REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segment 0, offset 0x798
0x98,
0x0f,
0x51, // REBASE_OPCODE_DO_REBASE_IMM_TIMES 1
0x00,
]);
rebases.copy(bytes, 0xf80);
bytes.writeUInt32LE(0xf80, 192);
bytes.writeUInt32LE(rebases.length, 196);
};
const protocolFacts = (bytes: Buffer) => {
const result = decodeAppleDispatchMetadata(bytes, 100, provenance);
return {
protocols: result.objc_protocols,
decode: result.objc_protocol_records.map(({ decode }) => decode),
coverage: result.coverage.find(
({ facet }) => facet === "objc_class_method_ivar_metadata",
),
};
};
it("marks a protocol partial when its class property list is a raw or rebased pointer", () => {
for (const withRebase of [false, true]) {
const bytes = protocolClassPropertiesImage(96, 0x600);
if (withRebase) {
withLegacyFixups(bytes);
rebaseClassProperties(bytes);
}
const { protocols, decode, coverage } = protocolFacts(bytes);
expect(protocols[0]?.properties.map(({ name }) => name)).toEqual([
"title",
]);
expect(decode).toEqual([
{
status: "partial",
reason: "protocol class properties are not decoded",
},
]);
expect(coverage).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"Protocol 0x100000740: Objective-C protocol FixtureProtocol properties: protocol class properties are not decoded",
),
});
}
});
it.each([
["raw null class property list", 96, 0, false],
["rebased null class property list", 96, 0, true],
[
"older protocol revision without _classProperties (88 bytes)",
88,
0x600,
false,
],
["protocol record ending before offset 96 (95 bytes)", 95, 0x600, false],
])(
"keeps a protocol decoded when it has a %s",
(_, size, classProperties, withRebase) => {
const bytes = protocolClassPropertiesImage(size, classProperties);
if (withRebase) {
withLegacyFixups(bytes);
rebaseClassProperties(bytes);
}
const { decode, coverage } = protocolFacts(bytes);
expect(decode).toEqual([{ status: "decoded", reason: null }]);
expect(coverage).toMatchObject({ status: "complete", reason: null });
},
);
it("reports a protocol class property list bound to another image as not decoded", () => {
const bytes = withLegacyFixups(protocolClassPropertiesImage(96, 0));
bindClassProperties(bytes, "_external_protocol_class_props");
const { protocols, decode, coverage } = protocolFacts(bytes);
expect(protocols[0]?.methods).toMatchObject([
{ selector: "requiredAction:" },
]);
expect(protocols[0]?.properties.map(({ name }) => name)).toEqual(["title"]);
expect(decode).toEqual([
{
status: "partial",
reason:
"protocol class properties are bound to _external_protocol_class_props and are not decoded",
},
]);
expect(coverage).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"Protocol 0x100000740: Objective-C protocol FixtureProtocol properties: protocol class properties are bound to _external_protocol_class_props and are not decoded",
),
});
});
it("does not read a zero protocol class property field as null when its fixups are unknown", () => {
const bytes = withLegacyFixups(protocolClassPropertiesImage(96, 0));
// An undecodable rebase stream leaves every raw pointer's fixup unknown.
bytes.writeUInt32LE(0xf80, 192);
bytes.writeUInt32LE(1, 196);
bytes.writeUInt8(0xf0, 0xf80);
const { decode, coverage } = protocolFacts(bytes);
expect(decode).toEqual([
{
status: "partial",
reason: expect.stringContaining(
"protocol class property list at 0x100000798: LC_DYLD_INFO pointer-fixup applicability was not completely decoded",
),
},
]);
expect(coverage).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"Protocol 0x100000740: Objective-C protocol FixtureProtocol properties: protocol class property list at 0x100000798: LC_DYLD_INFO pointer-fixup applicability was not completely decoded",
),
});
});
it("marks a nonzero protocol class property field not decoded when its fixups are unknown", () => {
const bytes = withLegacyFixups(protocolClassPropertiesImage(96, 0x600));
bytes.writeUInt32LE(0xf80, 192);
bytes.writeUInt32LE(1, 196);
bytes.writeUInt8(0xf0, 0xf80);
const { decode, coverage } = protocolFacts(bytes);
expect(decode).toEqual([
{
status: "partial",
reason: "protocol class properties are not decoded",
},
]);
expect(coverage).toMatchObject({ status: "partial" });
});
it("reports an unsupported fixup on a protocol class property field while retaining decoded facts", () => {
const bytes = withLegacyFixups(protocolClassPropertiesImage(96, 0));
bindClassProperties(bytes, "_external_protocol_class_props");
rebaseClassProperties(bytes);
const { protocols, decode, coverage } = protocolFacts(bytes);
expect(protocols[0]?.properties.map(({ name }) => name)).toEqual(["title"]);
expect(decode).toEqual([
{
status: "partial",
reason:
"protocol class property list at 0x100000798: Both bind and rebase records target pointer location 0x100000798",
},
]);
expect(coverage).toMatchObject({
status: "partial",
reason: expect.stringContaining(
"protocol class property list at 0x100000798: Both bind and rebase records target pointer location 0x100000798",
),
});
});
it("retains protocol facts when _classProperties is unmapped or instance properties also fail", () => {
const unmapped = protocolClassPropertiesImage(96, 0);
// Place the 96-byte protocol at 0xfa8 so its first 88 bytes are mapped and +88 lies at 0x1000 past the segment end.
unmapped.copy(unmapped, 0xfa8, 0x740, 0x798);
unmapped.writeBigUInt64LE(base + 0xfa8n, 0x708);
const unmappedFacts = protocolFacts(unmapped);
expect(unmappedFacts.protocols[0]).toMatchObject({
name: "FixtureProtocol",
methods: [{ selector: "requiredAction:" }],
properties: [{ name: "title" }],
});
expect(unmappedFacts.decode).toEqual([
{
status: "partial",
reason: expect.stringContaining(
"protocol class property list at 0x100001000:",
),
},
]);
expect(unmappedFacts.coverage).toMatchObject({ status: "partial" });
const bothFailed = withLegacyFixups(protocolClassPropertiesImage(96, 0));
bothFailed.writeBigUInt64LE(base + 0x5000n, 0x778); // unmapped instanceProperties
bindClassProperties(bothFailed, "_external_protocol_class_props");
const bothFacts = protocolFacts(bothFailed);
expect(bothFacts.protocols[0]).toMatchObject({
name: "FixtureProtocol",
methods: [{ selector: "requiredAction:" }],
properties: [],
});
expect(bothFacts.decode[0]?.status).toBe("partial");
expect(bothFacts.decode[0]?.reason).toContain("0x100005000");
expect(bothFacts.decode[0]?.reason).toContain(
"protocol class properties are bound to _external_protocol_class_props and are not decoded",
);
});
it("propagates unexpected errors thrown while resolving _classProperties", () => {
const result: Parameters<typeof decodeObjcDispatchFacets>[0]["result"] = {
objc_classes: [],
objc_protocols: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [],
swift_conformances: [],
swift_dispatch_slots: [],
swift_symbols: [],
relative_pointers: [],
coverage: [],
db_save_result: null,
};
const readers: Parameters<typeof decodeObjcDispatchFacets>[0]["readers"] = {
pointer: (addr) => {
if (addr === 0x1000n) return 0x2000n;
if (addr === 0x2008n) return 0x3000n;
return 0n;
},
u32: (addr) => (addr === 0x2040n ? 96 : 0),
u64: () => 0n,
i32: () => 0,
resolvePointer: () => {
throw new TypeError("unexpected fixup failure");
},
bound: () => undefined,
string: () => "FixtureProtocol",
location: (addr) => ({
address: `0x${addr.toString(16)}`,
file_offset: 0,
}),
evidence: (addr, description) => [
{
kind: "binary_metadata",
description,
location: { address: `0x${addr.toString(16)}`, file_offset: 0 },
artifact_path: "/fixture",
artifact_sha256: "0".repeat(64),
},
],
offset: () => 0,
};
expect(() =>
decodeObjcDispatchFacets({
sections: [{ name: "__objc_protolist", address: 0x1000n, size: 8 }],
segments: [],
readers,
budget: {
truncated: false,
admit: () => true,
isFull: () => false,
markTruncated: () => {},
},
maxListSlots: 10,
result,
}),
).toThrow(TypeError);
});
});
describe("Objective-C class method owner index parity", () => {
it("projects instance and class methods accurately across multiple classes without cross-class leakage", () => {
const result: Parameters<typeof decodeObjcDispatchFacets>[0]["result"] = {
objc_classes: [],
objc_protocols: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
objc_dispatch_implementations: [],
swift_conformances: [],
swift_dispatch_slots: [],
swift_symbols: [],
relative_pointers: [],
coverage: [],
db_save_result: null,
};
const classNames = ["Alpha", "Beta", "Alpha"]; // includes duplicate class name edge case
const segments = [
{
address: 0x1000000n,
size: 0x100000n,
offset: 0,
executable: true,
},
];
const sections = [
{
name: "__objc_classlist",
address: 0x20000n,
size: classNames.length * 8,
},
];
const readers: Parameters<typeof decodeObjcDispatchFacets>[0]["readers"] = {
pointer: (addr) => {
if (addr >= 0x20000n && addr < 0x20000n + BigInt(classNames.length * 8))
return 0x100000n + BigInt(Number((addr - 0x20000n) / 8n) * 256);
if (addr >= 0x100000n && addr < 0x101000n) {
const off = Number(addr - 0x100000n) % 256;
const baseAddr = addr - BigInt(off);
if (off === 0) return baseAddr + 128n;
if (off === 32) return baseAddr + 0x100000n;
if (off === 160) return baseAddr + 128n + 0x100000n;
return 0n;
}
if (addr >= 0x200000n && addr < 0x201000n) {
const rel = Number(addr - 0x200000n) % 256;
const baseAddr = addr - BigInt(rel);
if (rel === 24 || rel === 152) return baseAddr;
if (rel === 32) return baseAddr - 0x100000n + 0x200000n;
if (rel === 160) return baseAddr + 128n - 0x100000n + 0x200000n;
return 0n;
}
if (addr >= 0x300000n && addr < 0x301000n) {
const off = Number(addr & 0x7fn);
if (off === 8) return addr + 0x400000n;
if (off === 24) return 0x1000000n + (addr & 0xfffn);
}
return 0n;
},
u32: (addr) => {
if (addr >= 0x200000n && addr < 0x201000n) {
const rel = Number(addr - 0x200000n) % 256;
return rel === 0 || rel === 128 ? 2 : 0;
}
if (addr >= 0x300000n && addr < 0x301000n) {
const off = Number(addr & 0x7fn);
if (off === 0) return 24;
if (off === 4) return 1;
}
return 0;
},
u64: () => 0n,
i32: () => 0,
resolvePointer: () => ({ kind: "raw", target: 0n }),
bound: () => undefined,
string: (addr) => {
if (addr >= 0x200000n && addr < 0x201000n) {
const idx = Math.floor(Number(addr - 0x200000n) / 256);
return classNames[idx]!;
}
const meta = (Number(addr - 0x700000n) & 0x80) !== 0;
const idx = Math.floor(Number(addr - 0x700000n) / 256);
return `${classNames[idx]!}_${meta ? "cls" : "inst"}_${idx}`;
},
location: (addr) => ({
address: `0x${addr.toString(16)}`,
file_offset: 0,
}),
evidence: (addr, description) => [
{
kind: "binary_metadata",
description,
location: { address: `0x${addr.toString(16)}`, file_offset: 0 },
artifact_path: "/fixture",
artifact_sha256: "0".repeat(64),
},
],
offset: () => 0,
};
let budget = 1000;
decodeObjcDispatchFacets({
sections,
segments,
readers,
budget: {
truncated: false,
admit: () => budget-- > 0,
isFull: () => budget <= 0,
markTruncated: () => {},
},
maxListSlots: 100,
result,
});
expect(result.objc_classes).toHaveLength(6);
expect(result.objc_classes[0]!.methods.map((m) => m.selector)).toEqual([
"Alpha_inst_0",
]);
expect(result.objc_classes[1]!.methods.map((m) => m.selector)).toEqual([
"Alpha_cls_0",
]);
expect(result.objc_classes[2]!.methods.map((m) => m.selector)).toEqual([
"Beta_inst_1",
]);
expect(result.objc_classes[3]!.methods.map((m) => m.selector)).toEqual([
"Beta_cls_1",
]);
// Duplicate class name sees prior entries for same (class_name, method_type), matching filter parity.
expect(result.objc_classes[4]!.methods.map((m) => m.selector)).toEqual([
"Alpha_inst_0",
"Alpha_inst_2",
]);
});
});