perf(objc): streamline exact class identity projection (#13897)

This commit is contained in:
morluto authored and GitHub committed 2026-11-23 03:12:28 +00:00
1 parent 8e379a31d8
commit cdca45c270
3 files changed
+206 -315

No files matched your search

+69 -101
View File
@@ -7,8 +7,10 @@ import {
} from "../ports/AnalysisProvider.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { EnhancedTools } from "./EnhancedTools.js";
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
import { objcSwiftMetadataSchema } from "../domain/native/objcSwiftMetadata.js";
import {
objcSwiftMetadataSchema,
type MachoImportBinding,
} from "../domain/native/objcSwiftMetadata.js";
import { err, ok } from "../domain/result.js";
import {
AnalysisCapabilityUnavailableError,
@@ -40,27 +42,28 @@ const subject = {
architecture: "arm64" as const,
};
const classImport: MachoImportBinding = {
requested_address: "0x1000",
symbol: "_OBJC_CLASS_$_Document",
binding_source: "chained",
library_ordinal: 1,
library: "/System/Library/Frameworks/AppKit.framework/AppKit",
weak: false,
addend: "0",
};
const createPort = (
nativeOverrides: Partial<{
sha256: string;
architecture: BinaryArchitecture;
names: Array<{ address: string; value: string }>;
nameLimitations: string[];
metadataFailure: AnalysisError;
bindings: Array<{
requested_address: string;
symbol: string;
binding_source: "chained" | "bind" | "weak" | "lazy";
library_ordinal: number;
library: string | null;
weak: boolean;
addend: string;
}>;
bindings: MachoImportBinding[];
targetSelection: MachoTargetSelection | null;
nameProfile: boolean;
}> = {},
): AnalysisOperationPort => ({
execute: async (operation: AnalysisOperation, parameters) => {
execute: async (operation: AnalysisOperation) => {
if (operation === "list_names")
return ok(
createAnalysisExecution(
@@ -87,35 +90,13 @@ const createPort = (
),
);
expect(parameters).toMatchObject({
max_records: 20_000,
objc_class_import_addresses: [
...new Set(
(
nativeOverrides.names ?? [
{ address: "0x1000", value: "OBJC_CLASS_$_Document$GOT" },
{ address: "0x1000", value: "OBJC_CLASS_$_Document" },
]
).map(({ address }) => address),
),
],
objc_class_import_addresses_complete: true,
});
if (nativeOverrides.metadataFailure !== undefined)
return err(nativeOverrides.metadataFailure);
const result = objcSwiftMetadataSchema.parse({ db_save_result: null });
if (nativeOverrides.targetSelection !== null)
result.target_selection = nativeOverrides.targetSelection ?? selection;
result.objc_class_import_bindings = nativeOverrides.bindings ?? [
{
requested_address: "0x1000",
symbol: "_OBJC_CLASS_$_Document",
binding_source: "chained",
library_ordinal: 1,
library: "/System/Library/Frameworks/AppKit.framework/AppKit",
weak: false,
addend: "0",
},
classImport,
];
result.objc_class_import_binding_coverage = {
facet: "objc_class_import_bindings",
@@ -128,7 +109,7 @@ const createPort = (
createAnalysisExecution(
{
target_sha256: nativeOverrides.sha256 ?? sha256,
target_architecture: nativeOverrides.architecture ?? "arm64",
target_architecture: subject.architecture,
provider,
analysis_profile_digest: null,
result,
@@ -140,9 +121,6 @@ const createPort = (
...(nativeOverrides.sha256 === undefined
? {}
: { sha256: nativeOverrides.sha256 }),
...(nativeOverrides.architecture === undefined
? {}
: { architecture: nativeOverrides.architecture }),
},
},
),
@@ -218,7 +196,17 @@ it("reports no applicable identity scan when names contain no owned class labels
describe("Objective-C class import identity composition", () => {
it("joins only exact same-target bind slots and preserves literal filter selection", async () => {
const tools = new EnhancedTools(createPort());
const execute = vi.fn(
createPort({
names: [
{ address: "0x1000", value: "OBJC_CLASS_$_Document$GOT" },
{ address: "0x1000", value: "OBJC_CLASS_$_Document" },
{ address: "0x2000", value: "OBJC_CLASS_$_Other" },
{ address: "0x3000", value: "PTR__OBJC_CLASS_$_Other$GOT" },
],
}).execute,
);
const tools = new EnhancedTools({ execute });
await expect(
tools.executeValidated({
name: "get_objc_classes",
@@ -227,7 +215,7 @@ describe("Objective-C class import identity composition", () => {
).resolves.toMatchObject({
ok: true,
value: {
count: 1,
count: 2,
classes: [
{
address: "0x1000",
@@ -237,6 +225,7 @@ describe("Objective-C class import identity composition", () => {
slot_addresses: ["0x1000"],
},
},
{ address: "0x2000", name: "OBJC_CLASS_$_Other" },
],
identity_coverage: { status: "complete", reason: null },
},
@@ -268,6 +257,22 @@ describe("Objective-C class import identity composition", () => {
identity_coverage: { status: "complete", reason: null },
},
});
expect(
execute.mock.calls.flatMap(([operation, input]) =>
operation === "inspect_native_dispatch_metadata" ? [input] : [],
),
).toEqual([
{
max_records: 20_000,
objc_class_import_addresses: ["0x1000", "0x2000"],
objc_class_import_addresses_complete: true,
},
{
max_records: 20_000,
objc_class_import_addresses: ["0x1000"],
objc_class_import_addresses_complete: true,
},
]);
});
it("keeps rows unjoined when the native observation has a different subject", async () => {
@@ -398,53 +403,27 @@ describe("Objective-C class import coverage and failures", () => {
});
});
it("preserves same-named rows whose exact import slots have different identities", async () => {
const addresses = ["0x1000", "0x2000", "0x3000", "0x4000"];
it("preserves same-named rows with different exact import identities", async () => {
const name = "OBJC_CLASS_$_Document";
const bindings = [
classImport,
{ ...classImport, requested_address: "0x2000", library: "/other/UI.dylib" },
{ ...classImport, requested_address: "0x3000", weak: true },
{ ...classImport, requested_address: "0x4000", addend: "1" },
{
...classImport,
requested_address: "0x5000",
symbol: "_OBJC_CLASS_$_Other",
},
];
const rows = bindings.map(({ requested_address }) => ({
address: requested_address,
value: name,
}));
const tools = new EnhancedTools(
createPort({
names: [
...addresses.map((address) => ({ address, value: name })),
{ address: "0x1000", value: name },
],
bindings: [
{
requested_address: "0x1000",
symbol: "_OBJC_CLASS_$_Document",
binding_source: "chained",
library_ordinal: 1,
library: "/System/Library/Frameworks/AppKit.framework/AppKit",
weak: false,
addend: "0",
},
{
requested_address: "0x2000",
symbol: "_OBJC_CLASS_$_Document",
binding_source: "chained",
library_ordinal: 1,
library: "/System/Library/Frameworks/UIKit.framework/UIKit",
weak: false,
addend: "0",
},
{
requested_address: "0x3000",
symbol: "_OBJC_CLASS_$_Document",
binding_source: "chained",
library_ordinal: 1,
library: "/System/Library/Frameworks/AppKit.framework/AppKit",
weak: true,
addend: "0",
},
{
requested_address: "0x4000",
symbol: "_OBJC_CLASS_$_Document",
binding_source: "chained",
library_ordinal: 1,
library: "/System/Library/Frameworks/AppKit.framework/AppKit",
weak: false,
addend: "1",
},
],
names: [...rows, { address: "0x1000", value: name }],
bindings,
}),
);
@@ -456,22 +435,11 @@ it("preserves same-named rows whose exact import slots have different identities
).resolves.toMatchObject({
ok: true,
value: {
count: 4,
classes: addresses.map((address, index) => ({
address,
count: 5,
classes: bindings.map(({ requested_address, ...identity }) => ({
address: requested_address,
name,
binding_identity: {
symbol: "_OBJC_CLASS_$_Document",
binding_source: "chained",
library_ordinal: 1,
library:
index === 1
? "/System/Library/Frameworks/UIKit.framework/UIKit"
: "/System/Library/Frameworks/AppKit.framework/AppKit",
weak: index === 2,
addend: index === 3 ? "1" : "0",
slot_addresses: [address],
},
binding_identity: { ...identity, slot_addresses: [requested_address] },
})),
identity_coverage: { status: "complete", reason: null },
},
+57 -96
View File
@@ -17,15 +17,6 @@ const classImport = {
};
describe("Objective-C class label discovery", () => {
it("does not reinterpret a provider-specific label without an owner tag", () => {
expect(
selectObjcClassCandidates(
[{ address: "0x1", name: "__objc_class_HuntRoot_class" }],
"Hunt",
),
).toEqual([]);
});
it("uses provider-tagged stripped class labels and filters their exact text", () => {
const labels = [
"__objc_class_HuntRoot_class",
@@ -47,23 +38,44 @@ describe("Objective-C class label discovery", () => {
: {}),
}));
expect(selectObjcClassCandidates(names, "Hunt")).toEqual(names.slice(0, 6));
expect(
selectObjcClassCandidates(names, "__objc_class_HuntRoot_class"),
).toEqual([names[0]]);
const [root, ...siblings] = names;
const sameName = { ...root!, address: "0x40", name: labels[0]! };
const unowned = { address: "0x41", name: labels[0]! };
const inventory = [root!, unowned, sameName, root!, ...siblings];
expect(selectObjcClassCandidates(inventory, "Hunt")).toEqual([
root,
sameName,
...siblings.slice(0, 5),
]);
expect(selectObjcClassCandidates(inventory, labels[0]!)).toEqual([
root,
sameName,
]);
});
it("coalesces only selected rows whose own addresses prove the same import", () => {
it("keeps group order while selecting the first proven canonical row", () => {
const alias = { address: "0x1000", name: "OBJC_CLASS_$_Document$GOT" };
const canonical = { address: "0x1000", name: "OBJC_CLASS_$_Document" };
const unrelated = { address: "0x2000", name: "OBJC_CLASS_$_Document" };
const plain = { address: "0x2000", name: "OBJC_CLASS_$_Document" };
const canonical = { address: "0x1008", name: "OBJC_CLASS_$_Document" };
const laterCanonical = { ...canonical, address: "0x1010" };
const canonicalImport = {
...classImport,
requested_address: canonical.address,
};
const scan = {
bindings: [classImport],
bindings: [
canonicalImport,
classImport,
{ ...classImport, requested_address: laterCanonical.address },
canonicalImport,
],
coverage: completeCoverage,
};
expect(
projectObjcClassCandidates([alias, canonical, unrelated], scan),
projectObjcClassCandidates(
[alias, plain, canonical, laterCanonical],
scan,
),
).toEqual({
count: 2,
classes: [
@@ -76,107 +88,56 @@ describe("Objective-C class label discovery", () => {
library: classImport.library,
weak: false,
addend: "0",
slot_addresses: ["0x1000"],
slot_addresses: [
canonical.address,
alias.address,
laterCanonical.address,
],
},
},
unrelated,
plain,
],
identity_coverage: completeCoverage,
});
});
it("does not join same-name rows without exact slot evidence", () => {
const alias = { address: "0x1000", name: "OBJC_CLASS_$_Document$GOT" };
const canonical = { address: "0x2000", name: "OBJC_CLASS_$_Document" };
const secondAlias = { ...canonical, name: "OBJC_CLASS_$_Document$ptr" };
expect(
projectObjcClassCandidates([alias, canonical], {
bindings: [classImport],
coverage: completeCoverage,
projectObjcClassCandidates([alias, secondAlias], {
...scan,
bindings: [canonicalImport, classImport],
}),
).toMatchObject({ count: 2, classes: [alias, canonical] });
});
it("keeps rows separate when equal symbols have different bind identities", () => {
const rows = [
{ address: "0x1000", name: "OBJC_CLASS_$_Document$GOT" },
{ address: "0x2000", name: "OBJC_CLASS_$_Document$GOT" },
];
expect(
projectObjcClassCandidates(rows, {
bindings: [
classImport,
{
...classImport,
requested_address: "0x2000",
library: "/other/framework.dylib",
},
],
coverage: completeCoverage,
}),
).toMatchObject({ count: 2, classes: rows });
});
it("deduplicates exact class labels while keeping distinct addresses", () => {
const rows = [
{ address: "0x1000", name: "OBJC_CLASS_$_Document" },
{ address: "0x1000", name: "OBJC_CLASS_$_Document" },
{ address: "0x2000", name: "OBJC_CLASS_$_Document" },
];
expect(selectObjcClassCandidates(rows, "")).toEqual([rows[0], rows[2]]);
).toMatchObject({ count: 1, classes: [alias] });
});
});
it("keeps equal symbols separate when only their lookup ordinals differ", () => {
it.each([
["library_ordinal", -1, -2],
["binding_source", "bind", "weak"],
] as const)("keeps equal symbols separate across %s", (field, left, right) => {
const rows = [
{ address: "0x1000", name: "OBJC_CLASS_$_Document$GOT" },
{ address: "0x2000", name: "OBJC_CLASS_$_Document$GOT" },
];
const binding = { ...classImport, library_ordinal: 0, library: null };
expect(
projectObjcClassCandidates(rows, {
bindings: [
{ ...classImport, library_ordinal: -1, library: null },
{
...classImport,
requested_address: "0x2000",
library_ordinal: -2,
library: null,
},
{ ...binding, [field]: left },
{ ...binding, [field]: right, requested_address: "0x2000" },
],
coverage: completeCoverage,
}),
).toMatchObject({
count: 2,
classes: [
{ ...rows[0], binding_identity: { library_ordinal: -1 } },
{ ...rows[1], binding_identity: { library_ordinal: -2 } },
],
});
});
it("keeps regular self-scope and weak rebinding records separate", () => {
const rows = [
{ address: "0x1000", name: "OBJC_CLASS_$_Document$GOT" },
{ address: "0x2000", name: "OBJC_CLASS_$_Document$GOT" },
];
expect(
projectObjcClassCandidates(rows, {
bindings: [
{ ...classImport, library_ordinal: 0, library: null },
{
...classImport,
requested_address: "0x2000",
binding_source: "weak",
library_ordinal: 0,
library: null,
},
],
coverage: completeCoverage,
}),
).toMatchObject({
count: 2,
classes: [
{ ...rows[0], binding_identity: { binding_source: "bind" } },
{ ...rows[1], binding_identity: { binding_source: "weak" } },
{
...rows[0],
binding_identity: { [field]: left, slot_addresses: ["0x1000"] },
},
{
...rows[1],
binding_identity: { [field]: right, slot_addresses: ["0x2000"] },
},
],
});
});
+80 -118
View File
@@ -26,19 +26,24 @@ export interface ObjcClassImportBindingScan {
export const selectObjcClassCandidates = (
names: readonly AddressedName[],
pattern: string,
): AddressedName[] =>
uniqueByAddressAndName(
names
.filter(
({ name, objc_class_label }) =>
objcClassSymbol(name)?.metaclass === false ||
objc_class_label === "hopper_legacy_class_object" ||
(name.startsWith(LEGACY_OBJC_CLASS_PREFIX) &&
name.length > LEGACY_OBJC_CLASS_PREFIX.length &&
!/^l_OBJC_CLASS_NAME_(?:\.\d+)?$/u.test(name)),
)
.filter(({ name }) => pattern.length === 0 || name.includes(pattern)),
);
): AddressedName[] => {
const seen = new Set<string>();
return names.filter(({ address, name, objc_class_label }) => {
if (pattern.length > 0 && !name.includes(pattern)) return false;
const classLabel =
objcClassSymbol(name)?.metaclass === false ||
objc_class_label === "hopper_legacy_class_object" ||
(name.startsWith(LEGACY_OBJC_CLASS_PREFIX) &&
name.length > LEGACY_OBJC_CLASS_PREFIX.length &&
!/^l_OBJC_CLASS_NAME_(?:\.\d+)?$/u.test(name));
if (!classLabel) return false;
// Keep equal labels at distinct addresses until their slot identity is known.
const key = JSON.stringify([address, name]);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
};
/** Project selected class labels, coalescing only exact proven import identities. */
export const projectObjcClassCandidates = (
@@ -48,7 +53,7 @@ export const projectObjcClassCandidates = (
const classes = coalesceBoundClassAliases(candidates, bindingScan.bindings);
return {
count: classes.length,
classes: classes.map(toObjcClassEntry),
classes,
identity_coverage: {
status: bindingScan.coverage.status,
reason: bindingScan.coverage.reason,
@@ -188,105 +193,82 @@ const uniqueByName = (entries: readonly AddressedName[]): AddressedName[] => {
});
};
/** Keep same-named rows at distinct locations until slot identity is examined. */
const uniqueByAddressAndName = (
entries: readonly AddressedName[],
): AddressedName[] => {
const seen = new Set<string>();
return entries.filter(({ address, name }) => {
const key = JSON.stringify([address, name]);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
};
interface ObjcClassOutputEntry extends AddressedName {
readonly binding_identity?: Omit<MachoImportBinding, "requested_address"> & {
readonly slot_addresses: readonly string[];
};
interface ObjcClassBindingGroup {
readonly identity: MachoImportBinding;
readonly slotAddresses: Set<string>;
readonly canonicalSymbol: string | undefined;
representative: AddressedName | undefined;
canonical: boolean;
}
const coalesceBoundClassAliases = (
candidates: readonly AddressedName[],
bindings: readonly MachoImportBinding[],
): ObjcClassOutputEntry[] => {
const bindingsByAddress = new Map(
bindings.map((binding) => [binding.requested_address, binding]),
);
const bindingKey = (binding: MachoImportBinding) =>
JSON.stringify([
binding.symbol,
binding.binding_source,
binding.library_ordinal,
binding.library,
binding.weak,
binding.addend,
): JsonValue[] => {
const groupByIdentity = new Map<string, ObjcClassBindingGroup>();
const groupByAddress = new Map<string, ObjcClassBindingGroup>();
for (const identity of bindings) {
const key = JSON.stringify([
identity.symbol,
identity.binding_source,
identity.library_ordinal,
identity.library,
identity.weak,
identity.addend,
]);
const groupedBindings = new Map<string, MachoImportBinding[]>();
for (const binding of bindings) {
const key = bindingKey(binding);
const existing = groupedBindings.get(key);
if (existing === undefined) groupedBindings.set(key, [binding]);
else existing.push(binding);
let group = groupByIdentity.get(key);
if (group === undefined) {
group = {
identity,
slotAddresses: new Set(),
canonicalSymbol: classNameFromImport(identity.symbol),
representative: undefined,
canonical: false,
};
groupByIdentity.set(key, group);
}
group.slotAddresses.add(identity.requested_address);
groupByAddress.set(identity.requested_address, group);
}
const groupedCandidates = new Map<string, AddressedName[]>();
const ordered: Array<AddressedName | { readonly group: string }> = [];
const ordered: Array<AddressedName | ObjcClassBindingGroup> = [];
for (const candidate of candidates) {
const binding = bindingsByAddress.get(candidate.address);
if (binding === undefined) {
const group = groupByAddress.get(candidate.address);
if (group === undefined) {
ordered.push(candidate);
continue;
}
const key = bindingKey(binding);
let group = groupedCandidates.get(key);
if (group === undefined) {
group = [];
groupedCandidates.set(key, group);
ordered.push({ group: key });
if (group.representative === undefined) {
group.representative = candidate;
ordered.push(group);
}
if (
!group.canonical &&
group.canonicalSymbol !== undefined &&
classNameFromImport(candidate.name) === group.canonicalSymbol
) {
group.representative = candidate;
group.canonical = true;
}
group.push(candidate);
}
const output: ObjcClassOutputEntry[] = [];
for (const entry of ordered) {
if ("group" in entry) {
const key = entry.group;
const facts = groupedBindings.get(key) ?? [];
const group = groupedCandidates.get(key) ?? [];
const identity = facts[0];
const canonicalName =
identity === undefined
? undefined
: classNameFromImport(identity.symbol);
const representative =
(canonicalName === undefined
? undefined
: group.find(
({ name }) => classNameFromDisplayName(name) === canonicalName,
)) ?? group[0];
if (representative === undefined || identity === undefined) continue;
output.push({
...representative,
binding_identity: {
symbol: identity.symbol,
binding_source: identity.binding_source,
library_ordinal: identity.library_ordinal,
library: identity.library,
weak: identity.weak,
addend: identity.addend,
slot_addresses: [
...new Set(facts.map(({ requested_address }) => requested_address)),
],
},
});
} else {
const candidate = entry;
output.push(candidate);
}
}
return output;
return ordered.map((entry) => {
if (!("identity" in entry)) return toJsonEntry(entry);
const { identity, representative, slotAddresses } = entry;
return {
address: representative!.address,
name: representative!.name,
binding_identity: {
symbol: identity.symbol,
binding_source: identity.binding_source,
library_ordinal: identity.library_ordinal,
library: identity.library,
weak: identity.weak,
addend: identity.addend,
slot_addresses: [...slotAddresses],
},
};
});
};
const classNameFromImport = (symbol: string): string | undefined => {
@@ -294,26 +276,6 @@ const classNameFromImport = (symbol: string): string | undefined => {
return facts?.metaclass === false ? facts.symbol : undefined;
};
const classNameFromDisplayName = classNameFromImport;
const toObjcClassEntry = (entry: ObjcClassOutputEntry): JsonValue => ({
address: entry.address,
name: entry.name,
...(entry.binding_identity === undefined
? {}
: {
binding_identity: {
symbol: entry.binding_identity.symbol,
binding_source: entry.binding_identity.binding_source,
library_ordinal: entry.binding_identity.library_ordinal,
library: entry.binding_identity.library,
weak: entry.binding_identity.weak,
addend: entry.binding_identity.addend,
slot_addresses: [...entry.binding_identity.slot_addresses],
},
}),
});
const toJsonEntry = ({ address, name }: AddressedName): JsonValue => ({
address,
name,