Files
rea/tests/boundary/filesystem/elfSectionOverlap.test.ts
T
Entrpiandmorluto 5e56bd0a23 fix(ghidra)!: load ESP-IDF flash code in Ghidra's default address space (#8464)
* fix(ghidra)!: load ESP-IDF flash code in Ghidra's default address space

ESP-IDF's linker script reserves the addresses of .flash.text with the
NOBITS section .flash_rodata_dummy. Ghidra 12.1.4's ELF loader gives the
default address space to the later section, so .flash.text lands in an
overlay that its DWARF import, call-frame processing and default-space
references do not reach. Flash functions lose their DWARF signatures,
locals and no-return flags, each gets a one-byte shadow function in the
reservation, and pseudocode runs past calls such as esp_restart().

The ELF reader now records allocated ranges that an executable section
shares with another section, through one section-table visitor that the
RISC-V ISA reader also uses. When a NOBITS section starts with one
executable section and covers it, the RISC-V lanes commit both sections
to the analysis profile. ReaGhidraPrepareElfLoad.java then gives the code
the default address space before auto-analysis and keeps the reservation
as an uninitialized overlay; bytes, file offsets, symbols, functions and
entry points are kept. The session reports the outcome, and any memory
map that differs from the committed plan is refused. Images without such
an overlap keep their analysis profiles byte for byte.

BREAKING CHANGE: RISC-V images with this layout, such as ESP-IDF
ESP32-C6, H2 and H21 builds, report flash code at its ELF address
(0x42...) instead of .flash.text:0x42..., and their analysis profiles
change. RISC-V images with any other section overlap that involves
executable code are now refused with the overlapping sections named.
These include ESP-IDF v5.5.2 ESP32-C5 and C61 builds, whose second
reservation, .ext_ram.dummy, also covers .flash.text. See
docs/ghidra-riscv.md.

* fix(ghidra): bound the overlap sweep and check the load preparation

Domain:
- Find section overlaps with one sort and sweep that stops at the second
  overlap involving executable code, and read the ISA and the overlap in
  one section-table pass.
- Record the two sections that cause a refusal as witnesses. The Ghidra
  lane owns the refusal text and names them with their ranges.

Ghidra lane:
- Check the preparation report before the first lazily started analysis
  call, as for the calling-convention report.
- The pre-analysis script removes the code's overlay entry points, checks
  that no symbol or reference remains in the old overlay range, and reports
  the counts of the result. Its report echoes the blocks it left, which the
  client compares with the committed sections. A failed move refuses and
  rethrows. Reservation labels mark no entry points.
- Session limitations no longer state a planned move after a canonical
  outcome.

Verification:
- The ESP fixture defines ESP-IDF's absolute text bounds and the
  reservation's label. The lane checks their addresses, the entry points,
  file-offset uniqueness and snapshot replay, a reservation-first build,
  a pre-analysis refusal through analyzeHeadless and a truncated
  double-float section table.
- Boundary tests cover the refusal witnesses, a 10,000-section table and
  an ELF64 table.

* fix(ghidra): retarget references into the moved ESP-IDF flash code

The move takes the references from the code's range but not the
references into it. Besides the entry points, Ghidra 12.1.4's loader
records one data reference from the .flash.text section header to the
code, which the new post-condition refused in the RISC-V lane. Retarget
plain memory references and entry points into the old range to the moved
code; any other kind stays behind and is refused.

Removing the reservation block keeps the references into its range, so
the pinned symbols' entry points need no re-add.

* fix(ghidra): move labels past the ESP-IDF flash code's end with it

Ghidra 12.1.4 places a section-relative symbol at the section's end, such
as ESP-IDF's _etext, in the code's overlay space one byte past the block.
The move covers the block only, so the label stayed in the overlay and
ended up in the reservation. Everything in the code's overlay space now
follows the code: references are retargeted, labels outside the block are
created again in the default space, and the post-condition checks the
whole space. The script refuses when another block shares that space.

The ESP fixture defines _etext, and the lane checks its address.

* fix(ghidra): check prepared blocks by coordinates and address spaces

The client compared the pre-script's echoed block names with the ELF
section names, although section names are display only: an unnamed
section's empty name never matches the name Ghidra gives its block, so
that preparation was refused. It also accepted any reported address
spaces. The check now compares addresses, sizes and the code's file
offset, and requires moved code to go from an overlay into the
program's default space while its reservation leaves it, and canonical
code to stay there. An unnamed section is labelled by its index.

The docs and the pre-script now state that a failure during the move
may be refused without its reason, and that an entry mark on a
reservation label stays at its default-space address. The docs give
the llvm-objcopy route for the refused C5 and C61 builds. The lane
checks that no other block maps any of the code's file bytes, and the
overlap tests add the C5 and C61 section shape.

* fix(ghidra): bound the sections the overlap check keeps

The overlap check kept one record per allocated, non-empty section, and
only the file size limited their number. NOBITS headers take no file
bytes, so a crafted 1 GB ELF32 table holds about 27 million of them.
The check now keeps at most 65,280 (SHN_LORESERVE, from which ELF
counts sections through section zero) and reports the overlap as
unavailable beyond that, which the RISC-V lanes refuse as they refuse
a table that cannot be read.

* fix(ghidra): check RISC-V handshake reports before any analysis call

A RISC-V session that committed neither a calling-convention policy nor
a load preparation started its bridge lazily on the first query other
than `health`. An `elf_load_preparation` or calling-convention report
that the profile did not commit was then never checked, and the query
returned its result. Every RISC-V session now starts through the
checked handshake, so such a report closes the session before any
analysis call, whatever the first query is. A double-float session that
reports a preparation, and one that reports a calling-convention
policy, are now tested with `list_procedures`; both fail without the
fix.

Admission, profile parameters and profile digests do not change. If
Ghidra exits during the first query of a double-float session, the
error now tells the caller to reopen the session, as other checked
sessions do.

* fix(ghidra): skip analysis after a refused ELF load preparation

A refused memory map only wrote the refusal, so headless Ghidra still
ran seeds, auto-analysis and post-script analysis on a program that REA
then discarded. The preparation now turns off headless auto-analysis when
it refuses; later pre-scripts and the bridge still run, so the session
reports the reason.

The swap also renamed the reservation's overlay space to the section's
raw name, so a reservation named like another address space, such as
the RISC-V default space ram, or containing characters Ghidra rejects,
failed after the move. The space now takes the name Ghidra's memory map
derives for an overlay block: ':' and whitespace become '_', and a name
in use gains .1, .2 and so on.

verify:ghidra:riscv drops -noanalysis from the refusal run and checks
that Ghidra analyzed nothing, and a seventh fixture names the
reservation ram and checks that it moves into the overlay space ram.1.

* test(ghidra): read the load preparation report before Ghidra's log suffix

* test(ghidra): pin unchanged RISC-V profiles at main's revisions

main's byte-search (#8840), data-type (#8602) and reference revisions change every
Ghidra profile. With those revisions reversed, the old pins hold.

* fix(ghidra): name the moved RISC-V guide in load-layout diagnostics

The overlap refusal, the load-layout limitation and the bridge comments
named docs/ghidra-riscv.md, which main moved to docs/providers/.

* test(ghidra): check load-preparation facts instead of sentences

The refusal, report-check and handshake tests compared whole messages.
They now check the sections, coordinates, spaces and counts each message
must state, and the handshake compares the session's limitations with
ghidraRiscvLoadPreparationLimitations. Rewording the messages passes;
dropping a count fails.

* fix(ghidra): give the ESP-IDF load preparation unused temporary names

The preparation created its temporary blocks as <name>.rea, so a disjoint
section already named that refused an otherwise admitted image. It now
takes the first unused <name>.rea[.N]. verify:ghidra:riscv gains an
esp-edge-names fixture with such a section.

* fix(ghidra): keep both final block names free during the ESP-IDF swap

The code's temporary block could take the removed reservation's name,
such as a reservation named <code>.rea, and the reservation's rename
back then collided. The picker now skips both final names.
verify:ghidra:riscv's esp-edge-names fixture names its reservation
.flash.text.rea beside a disjoint .flash.text.rea.1.

* test(ghidra): repin the overlap-free RISC-V digests for main's #8340

main's #8340 bumps call_relationship_coverage from v5 to v7, which changes
every Ghidra profile digest. With the revision reverted in place, the old
pins hold (79 of 79).

* test(ghidra): repin unchanged RISC-V digests for main's value-flow budgets

main's #9706 adds native_value_flow_projection to the shared analysis
semantics, which changes the profiles of images without a section overlap.
With that one revision removed, the previous pins hold (79 of 79).

* fix(ghidra): inspect RISC-V PIE section overlaps and refuse an unverified PIE reservation

Main admits RISC-V PIE, but this lane requires a section-overlap read
that the resolver made only for ET_EXEC, so every PIE was refused. A PIE's
section addresses are fixed offsets from its load base, so overlaps do not
depend on the base: read them for ET_DYN too. The NOBITS reservation
preparation is verified for ET_EXEC only, so a PIE that needs it is
refused. Main's producer identity now digests the bridge sources, so the
test that compared profile digests with main's is replaced by checking
that images without an overlap commit no load preparation.

* fix(ghidra): find an ESP-IDF reservation that Ghidra 12.2 marks executable

Ghidra 12.2 gives each section block the permissions of the first PT_LOAD
that contains its address, so a NOBITS reservation that shares the code's
addresses comes out executable and the preparation refused every ESP-IDF
image. Tell the reservation from the code by its missing bytes alone; the
displaced reservation is still made non-executable. The PIE refusal test
now uses the ELF64 lane, which admits PIE.

* fix(verify): read the ESP-IDF fixtures' identity where main's #11416 moved it

Evidence subjects and snapshot targets now carry their digest under
identity, as the rest of the RISC-V verifier reads it.

* docs(ghidra): describe the ESP-IDF load layout as verified on Ghidra 12.2

The real RISC-V lane now passes on Ghidra 12.2, whose ELF loader still puts
the code in an overlay when its reservation follows it. Name 12.2 where the
lane exercised that behaviour, and note that 12.2 can mark the reservation
executable. Measurements of Ghidra APIs the lane did not re-check keep
their 12.1.4 attribution.

* docs(domain): align RISC-V section-overlap JSDoc with ET_DYN inspection

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-24 14:17:44 +00:00

463 lines
14 KiB
TypeScript

import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import {
ghidraRiscvLoadPreparation,
ghidraRiscvUnsupportedReason,
} from "../../../src/ghidra/GhidraRiscvProfile.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const SHT_PROGBITS = 1;
const SHT_STRTAB = 3;
const SHT_NOBITS = 8;
const SHT_RISCV_ATTRIBUTES = 0x70000003;
const ALLOC = 0x2;
const WRITE_ALLOC = 0x3;
const EXEC_ALLOC = 0x6;
const SECTION_TABLE = 128;
// Deliberately outside BinaryTargetResolver's 4 KiB probe.
const PAYLOADS = 8192;
// ESP-IDF's ESP32-C6 base string, which the ilp32 lane admits.
const C6_ARCH =
"rv32i2p1_m2p0_a2p1_c2p0_zicsr2p0_zifencei2p0_zmmul1p0_zaamo1p0_zalrsc1p0";
interface Section {
readonly name: string;
readonly type: number;
readonly flags: number;
readonly address: number;
readonly size: number;
readonly payload?: Buffer;
}
const attributes = (): Buffer => {
const list = [5, ...Buffer.from(`${C6_ARCH}\0`, "latin1")];
const scoped = Buffer.alloc(5 + list.length);
scoped[0] = 1; // Tag_File
scoped.writeUInt32LE(scoped.length, 1);
scoped.set(list, 5);
const vendor = Buffer.from("riscv\0", "latin1");
const header = Buffer.alloc(5);
header[0] = 0x41;
header.writeUInt32LE(4 + vendor.length + scoped.length, 1);
return Buffer.concat([header, vendor, scoped]);
};
// ELF header and section header field offsets of each class.
const LAYOUTS = {
32: {
shoff: 32,
flags: 36,
ehsize: 52,
shentsize: 40,
counts: 40,
sh: { flags: 8, address: 12, offset: 16, size: 20 },
},
64: {
shoff: 40,
flags: 48,
ehsize: 64,
shentsize: 64,
counts: 52,
sh: { flags: 8, address: 16, offset: 24, size: 32 },
},
} as const;
/**
* A RISC-V image with these sections, its attributes and, unless `names` is
* false, a section-name table. ELF32 images declare the soft-float ABI and
* ELF64 images the double-float ABI, so each reaches an admitted lane.
*/
const elf = (
sections: readonly Section[],
options: {
readonly type?: number;
readonly names?: boolean;
readonly elfClass?: 32 | 64;
} = {},
): Buffer => {
const elfClass = options.elfClass ?? 32;
const layout = LAYOUTS[elfClass];
const all: Section[] = [
...sections,
{
name: ".riscv.attributes",
type: SHT_RISCV_ATTRIBUTES,
flags: 0,
address: 0,
size: 0,
payload: attributes(),
},
];
const names = Buffer.from(
`\0${[...all.map((section) => section.name), ".shstrtab"].join("\0")}\0`,
"latin1",
);
if (options.names !== false)
all.push({
name: ".shstrtab",
type: SHT_STRTAB,
flags: 0,
address: 0,
size: 0,
payload: names,
});
const filed = all.map((section) =>
section.type === SHT_NOBITS
? Buffer.alloc(0)
: (section.payload ?? Buffer.alloc(section.size, 0x13)),
);
const payloads = Math.max(
PAYLOADS,
SECTION_TABLE + (1 + all.length) * layout.shentsize,
);
const bytes = Buffer.alloc(
payloads + filed.reduce((total, payload) => total + payload.length, 0),
);
const word = (value: number, at: number): void => {
if (elfClass === 64) bytes.writeBigUInt64LE(BigInt(value), at);
else bytes.writeUInt32LE(value, at);
};
bytes.set([0x7f, 0x45, 0x4c, 0x46, elfClass === 64 ? 2 : 1, 1, 1]);
bytes.writeUInt16LE(options.type ?? 2, 16);
bytes.writeUInt16LE(243, 18); // EM_RISCV
bytes.writeUInt32LE(1, 20);
word(SECTION_TABLE, layout.shoff);
// RVC with the soft-float ABI, or with the double-float ABI.
bytes.writeUInt32LE(elfClass === 64 ? 0x5 : 0x1, layout.flags);
bytes.writeUInt16LE(layout.ehsize, layout.counts);
bytes.writeUInt16LE(layout.shentsize, layout.counts + 6);
// From SHN_LORESERVE on, ELF counts sections through section zero's size.
const count = 1 + all.length;
bytes.writeUInt16LE(count < 0xff00 ? count : 0, layout.counts + 8);
if (count >= 0xff00) word(count, SECTION_TABLE + layout.sh.size);
bytes.writeUInt16LE(
options.names === false ? 0 : all.length,
layout.counts + 10,
);
let offset = payloads;
let nameOffset = 1;
all.forEach((section, index) => {
const header = SECTION_TABLE + (1 + index) * layout.shentsize;
const payload = filed[index] ?? Buffer.alloc(0);
bytes.writeUInt32LE(nameOffset, header);
nameOffset += section.name.length + 1;
bytes.writeUInt32LE(section.type, header + 4);
word(section.flags, header + layout.sh.flags);
word(section.address, header + layout.sh.address);
word(offset, header + layout.sh.offset);
word(
section.type === SHT_NOBITS ? section.size : payload.length,
header + layout.sh.size,
);
payload.copy(bytes, offset);
offset += payload.length;
});
return bytes;
};
const resolve = async (bytes: Buffer) => {
const directory = await createTestTempDirectory("rea-elf-overlap-test-");
const path = join(directory, "fixture.elf");
await writeFile(path, bytes);
const resolved = await parseBinaryTarget(path);
if (!resolved.ok) throw resolved.error;
if (
resolved.value.kind !== "executable" ||
resolved.value.architecture !== "riscv"
)
throw new Error("Expected a resolved RISC-V executable");
return {
overlap: resolved.value.riscv.sectionOverlap,
refusal: ghidraRiscvUnsupportedReason(resolved.value),
preparation: ghidraRiscvLoadPreparation(resolved.value),
};
};
// The ESP-IDF v6.1 ESP32-C6 hello_world layout, scaled down: the NOBITS
// reservation starts with the code and covers it, and rodata follows.
const code: Section = {
name: ".flash.text",
type: SHT_PROGBITS,
flags: EXEC_ALLOC,
address: 0x42000020,
size: 0x40,
};
const reservation: Section = {
name: ".flash_rodata_dummy",
type: SHT_NOBITS,
flags: WRITE_ALLOC,
address: 0x42000020,
size: 0x100,
};
const rodata: Section = {
name: ".flash.rodata",
type: SHT_PROGBITS,
flags: ALLOC,
address: 0x42000120,
size: 0x10,
};
const iram: Section = {
name: ".iram0.text",
type: SHT_PROGBITS,
flags: EXEC_ALLOC,
address: 0x40800000,
size: 0x20,
};
describe("ELF section overlaps at target resolution", () => {
it("records ESP-IDF's code reservation and plans the memory-map preparation", async () => {
const { overlap, refusal, preparation } = await resolve(
elf([iram, code, reservation, rodata]),
);
expect(overlap).toEqual({
status: "code-reservation",
code: {
index: 2,
name: ".flash.text",
address: "0x42000020",
size: "0x40",
offset: "0x2020",
},
reservation: {
index: 3,
name: ".flash_rodata_dummy",
address: "0x42000020",
size: "0x100",
},
});
expect(refusal).toBeNull();
expect(preparation).toEqual({
policy: "nobits-reservation-overlay-v1",
code: overlap?.status === "code-reservation" ? overlap.code : undefined,
reservation:
overlap?.status === "code-reservation"
? overlap.reservation
: undefined,
});
});
it("keeps the reservation without names when the image has no name table", async () => {
const { overlap } = await resolve(
elf([code, reservation], { names: false }),
);
expect(overlap).toMatchObject({
status: "code-reservation",
code: { index: 1, name: null },
reservation: { index: 2, name: null },
});
});
it.each([
["separate code and data", [iram, code, rodata]],
[
"overlapping data sections",
[
code,
rodata,
{ ...rodata, name: ".flash.tdata", type: SHT_NOBITS, size: 0x8 },
],
],
] as const)("admits %s without a preparation", async (_label, sections) => {
const { overlap, refusal, preparation } = await resolve(elf(sections));
expect(overlap).toEqual({ status: "none" });
expect(refusal).toBeNull();
expect(preparation).toBeUndefined();
});
it("leaves relocatable images uninspected, since their addresses are not load addresses", async () => {
const { overlap, refusal } = await resolve(
elf([code, reservation], { type: 1 }),
);
expect(overlap).toBeUndefined();
expect(refusal).toContain(
"relocatable images need separate load verification",
);
});
});
describe("ELF section overlap refusals", () => {
const CODE = "`.flash.text` (executable, 0x42000020, 0x40 bytes)";
it.each([
[
"a reservation smaller than the code",
[code, { ...reservation, size: 0x20 }],
`${CODE} and \`.flash_rodata_dummy\` (NOBITS, 0x42000020, 0x20 bytes)`,
],
[
"a reservation that starts inside the code",
[code, { ...reservation, address: 0x42000030 }],
`${CODE} and \`.flash_rodata_dummy\` (NOBITS, 0x42000030, 0x100 bytes)`,
],
[
"two overlapping code sections",
[code, { ...code, name: ".flash.text2", address: 0x42000040 }],
`\`.flash.text2\` (executable, 0x42000040, 0x40 bytes) and ${CODE}`,
],
[
"an executable reservation",
[code, { ...reservation, flags: EXEC_ALLOC }],
`\`.flash_rodata_dummy\` (executable, NOBITS, 0x42000020, 0x100 bytes) and ${CODE}`,
],
// The pair of the verified shape is not the cause: the third section is.
[
"a reservation that also covers rodata",
[code, reservation, { ...rodata, address: 0x42000100 }],
"`.flash_rodata_dummy` (NOBITS, 0x42000020, 0x100 bytes) and `.flash.rodata` (0x42000100, 0x10 bytes)",
],
[
"code that also overlaps rodata",
[code, reservation, { ...rodata, address: 0x42000040 }],
`${CODE} and \`.flash.rodata\` (0x42000040, 0x10 bytes)`,
],
// ESP-IDF v5.5.2's C5 and C61 builds also reserve the code and rodata for external RAM.
[
"a second reservation over the code and rodata",
[
code,
reservation,
rodata,
{ ...reservation, name: ".ext_ram.dummy", size: 0x200 },
],
`${CODE} and \`.ext_ram.dummy\` (NOBITS, 0x42000020, 0x200 bytes)`,
],
[
"a second code reservation",
[
code,
reservation,
{ ...iram, address: 0x42000400 },
{ ...reservation, name: ".iram_dummy", address: 0x42000400 },
],
"`.iram0.text` (executable, 0x42000400, 0x20 bytes) and `.iram_dummy` (NOBITS, 0x42000400, 0x100 bytes)",
],
] as const)(
"refuses %s and names its cause",
async (_label, sections, named) => {
const { overlap, refusal, preparation } = await resolve(elf(sections));
expect(overlap?.status).toBe("unsupported");
expect(refusal).toContain(`Sections ${named} share addresses`);
expect(refusal).toContain(
"This lane prepares only one NOBITS section that starts at an executable PROGBITS section's address and covers it",
);
expect(refusal).toContain("docs/providers/ghidra-riscv.md");
expect(preparation).toBeUndefined();
},
);
});
describe("ELF section tables at the reader's bounds", () => {
it("stops at the second overlap in a table of 10,000 executable sections at one address", async () => {
const sections = Array.from({ length: 10_000 }, () => ({
...code,
size: 4,
}));
const { overlap, refusal } = await resolve(elf(sections, { names: false }));
expect(overlap).toEqual({
status: "unsupported",
witnesses: [
{
index: 2,
name: null,
address: "0x42000020",
size: "0x4",
nobits: false,
executable: true,
},
{
index: 1,
name: null,
address: "0x42000020",
size: "0x4",
nobits: false,
executable: true,
},
],
});
expect(refusal).toContain(
"Sections section [2] (executable, 0x42000020, 0x4 bytes) and section [1]",
);
});
// Disjoint NOBITS sections, so only the number of records matters.
const disjoint = (count: number): Section[] =>
Array.from({ length: count }, (_, index) => ({
...reservation,
address: 0x42000020 + index * 0x100,
}));
it("keeps 65,280 allocated sections, the most the overlap check keeps", async () => {
const { overlap, refusal } = await resolve(
elf(disjoint(0xff00), { names: false }),
);
expect(overlap).toEqual({ status: "none" });
expect(refusal).toBeNull();
});
it("refuses a table with more allocated sections than the overlap check keeps", async () => {
const { overlap, refusal } = await resolve(
elf(disjoint(0xff01), { names: false }),
);
expect(overlap).toEqual({
status: "unavailable",
reason:
"the section table declares more than 65280 allocated sections, the most the overlap check keeps",
});
expect(refusal).toContain(
"requires a readable section table: the section table declares more than 65280 allocated sections",
);
});
it("reads ELF64 section tables, with addresses beyond 32 bits", async () => {
const high = 0x1_4200_0020;
const { overlap, refusal, preparation } = await resolve(
elf(
[
{ ...code, address: high },
{ ...reservation, address: high },
],
{ elfClass: 64 },
),
);
expect(overlap).toEqual({
status: "code-reservation",
code: {
index: 1,
name: ".flash.text",
address: "0x142000020",
size: "0x40",
offset: "0x2000",
},
reservation: {
index: 2,
name: ".flash_rodata_dummy",
address: "0x142000020",
size: "0x100",
},
});
expect(refusal).toBeNull();
expect(preparation?.code.address).toBe("0x142000020");
});
// Double-float lanes read no ISA declaration; the resolver still refuses a
// table it cannot read before any lane sees the image.
it("rejects a truncated section table of a double-float image", async () => {
const directory = await createTestTempDirectory("rea-elf-overlap-test-");
const path = join(directory, "truncated.elf");
await writeFile(
path,
elf([code, reservation], { elfClass: 64 }).subarray(
0,
SECTION_TABLE + 64 * 2,
),
);
const resolved = await parseBinaryTarget(path);
expect(resolved.ok).toBe(false);
if (!resolved.ok)
expect(resolved.error.message).toContain(
"truncated ELF section header table",
);
});
});