feat(analysis-view): filter native exports and ELF dependencies by name prefix

Retained native-exports and elf-dependencies views matched only exact names, so counting the exports or imports in one namespace meant paging every row. Add name_prefixes to the exports collection and to every named elf-dependencies collection. A prefix filter combines with exact names, and coverage.total counts every match, so limit 1 returns a count. ELF export prefixes follow the exact-name identity rules: non-ASCII names compare their UTF-8 bytes, and names that are not valid UTF-8 never match. The tool descriptions now name the filter.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
This commit is contained in:
gensokyo-devandgensokyo-dev authored and Ysopwnable committed 2026-11-23 17:41:53 +08:00
1 parent bf8448cdfc
commit a148da56cc
6 files changed
+237 -26

No files matched your search

@@ -307,7 +307,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_elf_dependencies", evidenceEffects),
kind: "native-provider",
description:
"Inspect one explicit local ELF32/ELF64 ET_EXEC or ET_DYN image's load-time dynamic dependencies without executing it, invoking the dynamic loader, or opening a disassembler. Returns ordered DT_NEEDED libraries (duplicates preserved), DT_SONAME, DT_RPATH and DT_RUNPATH as written including $ORIGIN/$LIB/$PLATFORM tokens, decoded DT_FLAGS and DT_FLAGS_1, PT_INTERP, GNU version requirements and definitions, derived per-namespace version maxima, and undefined .dynsym imports joined to library@version when known. A missing PT_DYNAMIC is an observed empty inventory. Relocatable objects use inspect_kernel_module; core dumps use inspect_recorded_crash. Reads a stable regular file; cyclic version chains and exhausted named budgets return no partial success. Unreadable strings or missing tables are reported as partial coverage with issues; complete coverage never retains issues. Omitted/complete detail preserves inline delivery. Select detail summary to retain complete Evidence and return identity, counts and source coverage. Query inspect_analysis_view kind elf-dependencies, collection needed, versions, definitions, maxima or imports, with exact names/original indices, fields and matching-row pagination; collection issues takes original indices and pagination only. Portable on supported Node hosts.",
"Inspect one explicit local ELF32/ELF64 ET_EXEC or ET_DYN image's load-time dynamic dependencies without executing it, invoking the dynamic loader, or opening a disassembler. Returns ordered DT_NEEDED libraries (duplicates preserved), DT_SONAME, DT_RPATH and DT_RUNPATH as written including $ORIGIN/$LIB/$PLATFORM tokens, decoded DT_FLAGS and DT_FLAGS_1, PT_INTERP, GNU version requirements and definitions, derived per-namespace version maxima, and undefined .dynsym imports joined to library@version when known. A missing PT_DYNAMIC is an observed empty inventory. Relocatable objects use inspect_kernel_module; core dumps use inspect_recorded_crash. Reads a stable regular file; cyclic version chains and exhausted named budgets return no partial success. Unreadable strings or missing tables are reported as partial coverage with issues; complete coverage never retains issues. Omitted/complete detail preserves inline delivery. Select detail summary to retain complete Evidence and return identity, counts and source coverage. Query inspect_analysis_view kind elf-dependencies, collection needed, versions, definitions, maxima or imports, with exact names, name_prefixes, original indices, fields and matching-row pagination (coverage.total counts every match); collection issues takes original indices and pagination only. Portable on supported Node hosts.",
inputSchema: inspectElfDependenciesRequestSchema,
outputSchema: analysisDetailOutputSchemaOf(
elfDependenciesSchema,
@@ -446,7 +446,7 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_native_exports", evidenceEffects),
kind: "native-provider",
description:
"Inspect PE/ELF exports without execution or an analysis engine; use inspect_macho for Mach-O. Returns named/ordinal/forwarded PE exports or defined ELF dynamic symbols with binding/type/version, preserving aliases, hidden versions and raw-name qualifications. Without SHT_DYNSYM, ELF uses PT_DYNAMIC with DT_HASH or DT_GNU_HASH; an indeterminate symbol count is unsupported. Readable fallback version indices and hidden flags are retained; unresolved version names or unreadable entries make coverage partial. An empty complete inventory means no declared exports. detail summary retains full Evidence for inspect_analysis_view kind native-exports, collection exports/issues, with exact names/indices, fields and paging; source_index is parent-scoped.",
"Inspect PE/ELF exports without execution or an analysis engine; use inspect_macho for Mach-O. Returns named/ordinal/forwarded PE exports (ordinal, RVA, address) or defined ELF dynamic symbols with binding/type/version, preserving aliases, hidden versions and raw-name qualifications. Without SHT_DYNSYM, ELF uses PT_DYNAMIC with DT_HASH or DT_GNU_HASH; an indeterminate symbol count is unsupported. Readable fallback version indices and hidden flags are retained; unresolved version names or unreadable entries make coverage partial. An empty complete inventory means no declared exports. detail summary retains full Evidence for inspect_analysis_view kind native-exports, collection exports/issues, with exact names, name_prefixes, indices, fields and paging; coverage.total counts every match, so limit 1 returns a count. source_index is parent-scoped.",
inputSchema: inspectNativeExportsRequestSchema,
outputSchema: analysisDetailOutputSchemaOf(
nativeExportsSchema,
+13 -2
View File
@@ -12,6 +12,7 @@ import {
type SummaryAnalysisView,
} from "./analysisViewShape.js";
import { analysisViewInputError } from "./analysisViewErrors.js";
import { namePrefixesSchema, startsWithAny } from "./namePrefixFilter.js";
import { createAnalysisViewResultReader } from "./analysisViewParent.js";
import {
boundedViewMessages,
@@ -59,6 +60,7 @@ export const elfDependenciesViewRequestSchema = z.discriminatedUnion(
.describe(
"Exact DT_NEEDED names. Omitted includes all names; [] matches none.",
),
name_prefixes: namePrefixesSchema("DT_NEEDED names"),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(neededRow.keyof()).optional(),
}),
@@ -71,6 +73,7 @@ export const elfDependenciesViewRequestSchema = z.discriminatedUnion(
.describe(
"Exact version names. Omitted includes all names; [] matches none.",
),
name_prefixes: namePrefixesSchema("version names"),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(versionRowSchema.keyof()).optional(),
}),
@@ -83,6 +86,7 @@ export const elfDependenciesViewRequestSchema = z.discriminatedUnion(
.describe(
"Exact GNU version-definition names. Omitted includes all names; [] matches none.",
),
name_prefixes: namePrefixesSchema("GNU version-definition names"),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(definitionRow.keyof()).optional(),
}),
@@ -95,6 +99,7 @@ export const elfDependenciesViewRequestSchema = z.discriminatedUnion(
.describe(
"Exact version namespaces, such as GLIBC. Omitted includes all namespaces; [] matches none.",
),
name_prefixes: namePrefixesSchema("version namespaces"),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(maximumRow.keyof()).optional(),
}),
@@ -107,6 +112,7 @@ export const elfDependenciesViewRequestSchema = z.discriminatedUnion(
.describe(
"Exact undefined-symbol names. Omitted includes all names; [] matches none.",
),
name_prefixes: namePrefixesSchema("undefined-symbol names"),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(importRow.keyof()).optional(),
}),
@@ -271,6 +277,7 @@ export const projectElfDependenciesView = (
});
}
const names = view.names === undefined ? undefined : new Set(view.names);
const prefixes = view.name_prefixes;
const pageRows = <Row extends Record<string, unknown>>(
rows: readonly Row[],
allowed: readonly string[],
@@ -289,11 +296,15 @@ export const projectElfDependenciesView = (
source_index,
});
const matchesName =
names === undefined
names === undefined && prefixes === undefined
? undefined
: (row: Row) => {
const name = nameOf(row);
return name !== null && names.has(name);
return (
name !== null &&
(names === undefined || names.has(name)) &&
(prefixes === undefined || startsWithAny(name, prefixes))
);
};
const selected =
indices !== undefined
@@ -0,0 +1,16 @@
import { z } from "zod";
/** Caller-selected name prefixes; counts come from page coverage, not a separate facet. */
export const namePrefixesSchema = (rows: string) =>
z
.array(z.string().min(1))
.optional()
.describe(
`Name prefixes for ${rows}; a row matches when its name starts with any listed prefix, case-sensitively. With names, both must match. Omitted includes all names; [] matches none. coverage.total counts every match, so limit 1 returns the count.`,
);
/** Whether a known name starts with any selected prefix. */
export const startsWithAny = (
name: string,
prefixes: readonly string[],
): boolean => prefixes.some((prefix) => name.startsWith(prefix));
+61 -22
View File
@@ -13,6 +13,7 @@ import {
type SummaryAnalysisView,
} from "./analysisViewShape.js";
import { analysisViewInputError } from "./analysisViewErrors.js";
import { namePrefixesSchema, startsWithAny } from "./namePrefixFilter.js";
import { createAnalysisViewResultReader } from "./analysisViewParent.js";
import {
boundedViewMessages,
@@ -48,6 +49,9 @@ export const nativeExportsViewRequestSchema = z.discriminatedUnion(
.describe(
"Exact PE names, or UTF-8 ELF source names. ELF display fallbacks and names with unknown encoding are not identities; use indices for those rows. Omitted includes all names; [] matches none.",
),
name_prefixes: namePrefixesSchema(
"PE names or UTF-8 ELF source names; ELF names that are not valid UTF-8 never match",
),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(z.union([peRow.keyof(), elfRow.keyof()])).optional(),
}),
@@ -78,6 +82,62 @@ export const nativeExportsSummarySchema = z.discriminatedUnion("format", [
const readReport = createAnalysisViewResultReader(nativeExportsSchema);
type ExportRow = NativeExports["exports"][number];
/**
* Match exact names and name prefixes with the identity rules of each format.
* ELF identities are bytes: a non-ASCII name compares its exact UTF-8 bytes,
* and a name that is not valid UTF-8 has no text to match.
*/
const exportNameMatcher = (
selectedNames: readonly string[] | undefined,
prefixes: readonly string[] | undefined,
): ((row: ExportRow) => boolean) | undefined => {
if (selectedNames === undefined && prefixes === undefined) return undefined;
const names =
selectedNames === undefined ? undefined : new Set(selectedNames);
const encodedNames =
names === undefined
? undefined
: new Set(
[...names].flatMap((name) => {
const bytes = Buffer.from(name, "utf8");
return bytes.toString("utf8") === name
? [bytes.toString("base64")]
: [];
}),
);
// As for exact names, text that does not round-trip through UTF-8 (an
// unpaired surrogate) has no bytes to compare and matches nothing.
const prefixBytes = prefixes?.flatMap((prefix) => {
const bytes = Buffer.from(prefix, "utf8");
return bytes.toString("utf8") === prefix ? [bytes] : [];
});
const exact = (row: ExportRow): boolean =>
names === undefined ||
("name_utf8_decodable" in row
? row.name_utf8_decodable &&
(row.name_bytes_base64 !== null
? encodedNames!.has(row.name_bytes_base64)
: names.has(row.name))
: row.name !== null && names.has(row.name));
const prefixed = (row: ExportRow): boolean => {
if (prefixes === undefined) return true;
if (!("name_utf8_decodable" in row))
return row.name !== null && startsWithAny(row.name, prefixes);
if (!row.name_utf8_decodable) return false;
if (row.name_bytes_base64 === null)
return startsWithAny(row.name, prefixes);
const bytes = Buffer.from(row.name_bytes_base64, "base64");
return prefixBytes!.some(
(prefix) =>
bytes.length >= prefix.length &&
bytes.subarray(0, prefix.length).equals(prefix),
);
};
return (row) => exact(row) && prefixed(row);
};
/** Read selected export facts without reopening the artifact or reinterpreting its tables. */
export const projectNativeExportsView = (
parent: AnalysisViewParent,
@@ -170,18 +230,6 @@ export const projectNativeExportsView = (
return invalid(
`Selected export fields do not belong to ${report.format}; available fields: ${allowed.join(", ")}.`,
);
const names = view.names === undefined ? undefined : new Set(view.names);
const encodedNames =
names === undefined
? undefined
: new Set(
[...names].flatMap((name) => {
const bytes = Buffer.from(name, "utf8");
return bytes.toString("utf8") === name
? [bytes.toString("base64")]
: [];
}),
);
// A projected decoded name still carries its exact bytes and encoding qualification.
const columns = new Set<string>(fields);
if (report.format === "elf" && columns.has("name")) {
@@ -196,16 +244,7 @@ export const projectNativeExportsView = (
...pickFields(row, columns),
source_index,
});
const matchesName =
names === undefined
? undefined
: (row: NativeExports["exports"][number]) =>
"name_utf8_decodable" in row
? row.name_utf8_decodable === true &&
(row.name_bytes_base64 !== null
? encodedNames!.has(row.name_bytes_base64)
: names.has(row.name))
: row.name !== null && names.has(row.name);
const matchesName = exportNameMatcher(view.names, view.name_prefixes);
const selected =
indices !== undefined
? selectIndexedViewRows(rows, indices, view, matchesName, projectRow)
@@ -307,6 +307,7 @@ it("preserves PE ordinal-only, forwarder, alias and same-address distinctions",
source_index: 1,
name: "AliasB",
ordinal: 65536,
rva: 0x2000,
address: "0x180002000",
forwarder: null,
},
@@ -410,3 +411,127 @@ it("revalidates mutable imports and refuses inconsistent coverage and format-inc
).toBe(false);
expect(projectAnalysisView(parent({}), { kind: "summary" }).ok).toBe(false);
});
it("counts ELF exports by UTF-8 name prefix without matching undecodable names", () => {
const report = parseNativeExports(
elfExportImage({
symbols: [
{ name: "café" },
{ name: "café" },
{ name: "same" },
{ name: "sample" },
{ name: "other" },
],
}),
artifact,
);
const page = (view: Record<string, unknown>) =>
project(report, {
kind: "native-exports",
collection: "exports",
fields: ["name"],
...view,
});
// Index 1 displays as Latin-1 "café" but its bytes are not UTF-8 text.
expect(page({ name_prefixes: ["caf"] })).toMatchObject({
items: [{ source_index: 0, name: "café", name_utf8_decodable: true }],
coverage: { total: 1 },
});
expect(page({ name_prefixes: ["café"] })).toMatchObject({
items: [{ source_index: 0 }],
coverage: { total: 1 },
});
expect(page({ name_prefixes: ["sam", "oth"], limit: 1 })).toMatchObject({
items: [{ source_index: 2, name: "same" }],
coverage: { examined: 1, total: 3, next_offset: 1 },
});
expect(
page({ names: ["sample", "other"], name_prefixes: ["sam"] }),
).toMatchObject({
items: [{ source_index: 3, name: "sample" }],
coverage: { total: 1 },
});
expect(page({ name_prefixes: [] })).toMatchObject({
items: [],
coverage: { total: 0 },
});
});
it("counts PE exports by name prefix and skips ordinal-only exports", () => {
const report = parseNativeExports(
peExportImage({
functions: [{ rva: 0x2000 }, { rva: 0x2010 }, { rva: 0x2020 }],
names: [
{ name: "PyUnicode_New", index: 0 },
{ name: "PyUnicode_Concat", index: 1 },
],
}),
artifact,
);
expect(
project(report, {
kind: "native-exports",
collection: "exports",
name_prefixes: ["PyUnicode_"],
fields: ["name", "ordinal", "rva"],
limit: 1,
}),
).toMatchObject({
items: [{ name: "PyUnicode_New", rva: 0x2000 }],
exports: { export_count: 3 },
coverage: { total: 2, next_offset: 1 },
});
});
it("reads PE export Evidence saved before rows recorded their RVA", () => {
const report = parseNativeExports(
peExportImage({
functions: [{ rva: 0x2000 }],
names: [{ name: "PyUnicode_New", index: 0 }],
}),
artifact,
);
if (report.format !== "pe") throw new Error("Expected PE fixture");
const saved = {
...report,
exports: report.exports.map(({ rva: _rva, ...row }) => row),
};
expect(project(saved, { kind: "summary" })).toMatchObject({
summary: { export_count: 1 },
});
const page = project(saved, {
kind: "native-exports",
collection: "exports",
name_prefixes: ["PyUnicode_"],
});
expect(page).toMatchObject({
items: [{ name: "PyUnicode_New", source_index: 0 }],
coverage: { total: 1 },
});
if (!("items" in page)) throw new Error("Expected an export page");
expect((page.items as readonly object[])[0]).not.toHaveProperty("rva");
});
it("matches no ELF export for a prefix that is not well-formed UTF-16 and accepts long prefix lists", () => {
const report = parseNativeExports(
elfExportImage({ symbols: [{ name: "café" }, { name: "same" }] }),
artifact,
);
const page = (name_prefixes: string[]) =>
project(report, {
kind: "native-exports",
collection: "exports",
name_prefixes,
fields: ["name"],
});
// Buffer.from would encode the lone surrogate as U+FFFD instead.
expect(page(["\ud800"])).toMatchObject({ items: [], coverage: { total: 0 } });
const many = Array.from(
{ length: 100 },
(_, index) => `none${String(index)}`,
);
expect(page([...many, "sa"])).toMatchObject({
items: [{ source_index: 1, name: "same" }],
coverage: { total: 1 },
});
});
@@ -147,6 +147,26 @@ cliTest(
},
],
});
const prefixed = await call("inspect_analysis_view", {
...request,
view: {
...request.view,
collection: "imports",
names: undefined,
name_prefixes: ["pri"],
fields: ["name"],
offset: 0,
limit: 1,
},
});
expect(prefixed.isError, JSON.stringify(prefixed.content)).not.toBe(true);
expect(
viewContract.outputSchema.parse(prefixed.structuredContent)
.normalized_result,
).toMatchObject({
items: [{ source_index: 0, name: "printf" }],
coverage: { examined: 1, total: 1 },
});
const { view_digest, ...content } = projectedView;
expect(view_digest).toBe(digestCanonicalValue(content, "Analysis view"));
},