Files
reverse-engineering-anything/bridge/ghidra/ReaGhidraPrepareElfLoad.java
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

361 lines
19 KiB
Java

import com.google.gson.JsonObject;
import ghidra.app.script.ImproperUseException;
import ghidra.app.util.headless.HeadlessScript;
import ghidra.program.database.ProgramDB;
import ghidra.program.database.mem.FileBytes;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressFactory;
import ghidra.program.model.address.AddressIterator;
import ghidra.program.model.address.AddressSet;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.Memory;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.mem.MemoryBlockSourceInfo;
import ghidra.program.model.symbol.Namespace;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.symbol.ReferenceManager;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SymbolTable;
import ghidra.program.model.symbol.SymbolType;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Give an executable section that a NOBITS reservation shares addresses with the default address
* space before auto-analysis (docs/providers/ghidra-riscv.md). Ghidra 12.2's ELF loader resolves the
* overlap in favour of the later section, so ESP-IDF's .flash_rodata_dummy keeps the default space
* and .flash.text lands in an overlay, which DWARF import, call-frame entries and default-space
* references never reach. REA's TypeScript admission commits both sections, and the script refuses
* any other memory map, and then turns off headless auto-analysis, since REA discards the session.
* The file bytes and their offsets do not change.
*/
public final class ReaGhidraPrepareElfLoad extends HeadlessScript {
static final String POLICY = "nobits-reservation-overlay-v1";
static final String REPORT_KEY = "REA ELF load preparation";
/** The handshake bounds a refusal; this leaves room for the context around a failure. */
private static final int FAILURE_DETAIL_MAX = 512;
private record Label(String name, long offset, Namespace namespace, SourceType source) {}
@Override
public void run() throws Exception {
String[] arguments = getScriptArgs();
if (arguments.length != 6 || !arguments[0].equals(POLICY)) {
throw new IllegalArgumentException(
"ELF load preparation requires policy " + POLICY + " and the committed code and reservation sections"
);
}
long codeAddress = parseHex(arguments[1]);
long codeSize = parseHex(arguments[2]);
long codeOffset = parseHex(arguments[3]);
long reservationAddress = parseHex(arguments[4]);
long reservationSize = parseHex(arguments[5]);
if (codeSize == 0 || reservationAddress != codeAddress ||
Long.compareUnsigned(reservationSize, codeSize) < 0) {
throw new IllegalArgumentException(
"ELF load preparation requires a reservation that starts with the code and covers it"
);
}
Memory memory = currentProgram.getMemory();
AddressSpace space = currentProgram.getAddressFactory().getDefaultAddressSpace();
List<FileBytes> files = memory.getAllFileBytes();
if (files.size() != 1) {
refuse("Ghidra holds " + files.size() + " imported file images instead of one");
return;
}
FileBytes file = files.get(0);
MemoryBlock code = null;
MemoryBlock reservation = null;
int codeCandidates = 0;
for (MemoryBlock block : memory.getBlocks()) {
AddressSpace blockSpace = block.getStart().getAddressSpace();
if (block.getStart().getOffset() != codeAddress) continue;
if (block.isInitialized() && block.isExecute() && block.getSize() == codeSize &&
blockSpace.getPhysicalSpace() == space && mapsFile(block, file, codeOffset)) {
code = block;
codeCandidates++;
}
// Ghidra 12.2 gives a section the permissions of the first PT_LOAD that contains its
// address, so a reservation sharing the code's addresses can be executable: only its
// missing bytes tell it from the code. The displaced reservation is never executable.
if (!block.isInitialized() && blockSpace == space && block.getSize() == reservationSize) {
reservation = block;
}
}
String committed = "executable section " + hex(codeAddress) + " (" + hex(codeSize) +
" bytes at file offset " + hex(codeOffset) + ")";
if (codeCandidates != 1) {
refuse("Ghidra has " + codeCandidates + " initialized executable blocks for the committed " + committed);
return;
}
if (!code.isOverlay() && reservation == null) {
JsonObject result = new JsonObject();
result.add("code", echoCode(code, code.getStart().getAddressSpace().getName()));
report("canonical", result);
return;
}
if (!code.isOverlay() || reservation == null) {
refuse("Ghidra placed the committed " + committed + (code.isOverlay()
? " in an overlay, but no uninitialized default-space reservation " + hex(reservationAddress) +
" (" + hex(reservationSize) + " bytes) displaced it"
: " in the default space beside a reservation block"));
return;
}
// The code's whole overlay space moves with it and then becomes the reservation's.
for (MemoryBlock block : memory.getBlocks()) {
if (block != code && block.getStart().getAddressSpace().equals(code.getStart().getAddressSpace())) {
refuse("Ghidra placed block " + block.getName() + " in the overlay space of the committed " + committed);
return;
}
}
JsonObject moved;
try {
moved = swap(code, reservation, file, codeOffset, committed);
}
catch (Exception failure) {
// A failed swap can leave the program half moved: REA must not analyze it. If Ghidra
// rolls back the failed script's changes, the refusal goes too, and the missing report
// refuses the session instead (not tested).
refuse("Ghidra failed while moving the committed " + committed + ": " + detail(failure));
throw failure;
}
if (moved != null) report("moved", moved);
}
/**
* Ghidra 12.1.4 constraints: Memory.moveBlock keeps a block in its address space, and the
* native decompiler stops registering programs once any overlay space is removed. The code
* therefore moves by re-creating its block and moving program content, and its overlay space
* becomes the reservation's. Returns null after a refusal.
*/
private JsonObject swap(MemoryBlock code, MemoryBlock reservation, FileBytes file, long fileOffset,
String committed) throws Exception {
Memory memory = currentProgram.getMemory();
SymbolTable symbols = currentProgram.getSymbolTable();
AddressSpace space = currentProgram.getAddressFactory().getDefaultAddressSpace();
long size = code.getSize();
long reservationSize = reservation.getSize();
String codeName = code.getName();
String reservationName = reservation.getName();
AddressSpace overlaySpace = code.getStart().getAddressSpace();
String overlayName = overlaySpace.getName();
// Everything in the code's overlay space belongs to the code, including labels past its
// end, such as ESP-IDF's section-relative _etext.
AddressSet old = new AddressSet(overlaySpace.getMinAddress(), overlaySpace.getMaxAddress());
List<Label> labels = new ArrayList<>();
for (Symbol symbol : symbols.getSymbols(range(reservation), SymbolType.LABEL, true)) {
// Ghidra pins absolute ELF symbols: they keep their default-space address.
if (symbol.isPinned()) continue;
labels.add(new Label(
symbol.getName(),
symbol.getAddress().getOffset(),
symbol.getParentNamespace(),
symbol.getSource()
));
}
boolean reservationRead = reservation.isRead();
boolean reservationWrite = reservation.isWrite();
String reservationComment = reservation.getComment();
String reservationSource = reservation.getSourceName();
// Removing a block keeps the references into its range, entry points included.
memory.removeBlock(reservation, monitor);
MemoryBlock canonical = memory.createInitializedBlock(
unusedBlockName(codeName, codeName, reservationName), space.getAddress(code.getStart().getOffset()), file, fileOffset, size, false
);
canonical.setPermissions(code.isRead(), code.isWrite(), code.isExecute());
canonical.setVolatile(code.isVolatile());
canonical.setComment(code.getComment());
canonical.setSourceName(code.getSourceName());
((ProgramDB) currentProgram).moveAddressRange(code.getStart(), canonical.getStart(), size, monitor);
// The move takes symbols, functions and the references from the range, not the references
// into it, such as entry points and the loader's section-header reference: retarget them.
ReferenceManager references = currentProgram.getReferenceManager();
List<Reference> into = new ArrayList<>();
for (Address target : references.getReferenceDestinationIterator(old, true)) {
for (Reference reference : references.getReferencesTo(target)) into.add(reference);
}
for (Reference reference : into) {
Address target = space.getAddress(reference.getToAddress().getOffset());
if (reference.isEntryPointReference()) {
symbols.removeExternalEntryPoint(reference.getToAddress());
symbols.addExternalEntryPoint(target);
}
else if (reference.isMemoryReference() && !reference.isOffsetReference() &&
!reference.isShiftedReference()) {
references.delete(reference);
references.setPrimary(references.addMemoryReference(reference.getFromAddress(), target,
reference.getReferenceType(), reference.getSource(), reference.getOperandIndex()),
reference.isPrimary());
}
}
// The move covers the block; labels outside it are created again at the same offsets.
List<Symbol> outside = new ArrayList<>();
for (Symbol symbol : symbols.getSymbols(old, SymbolType.LABEL, true)) outside.add(symbol);
for (Symbol symbol : outside) {
symbols.createLabel(space.getAddress(symbol.getAddress().getOffset()), symbol.getName(),
symbol.getParentNamespace(), symbol.getSource());
symbol.delete();
}
// Any other kind of reference stays behind, as would a symbol the move missed: refuse both.
boolean symbolsLeft = symbols.getPrimarySymbolIterator(old, true).hasNext();
if (symbolsLeft || references.getReferenceDestinationIterator(old, true).hasNext()) {
refuse("Ghidra left " + (symbolsLeft ? "symbols" : "references") + " in overlay space " + overlayName +
" after moving the committed " + committed);
return null;
}
// The emptied overlay block becomes the reservation: no bytes and no file mapping.
MemoryBlock displaced = memory.convertToUninitialized(code);
if (reservationSize > size) {
MemoryBlock rest = memory.createUninitializedBlock(
unusedBlockName(reservationName, codeName, reservationName), displaced.getEnd().add(1), reservationSize - size, false
);
displaced = memory.join(displaced, rest);
}
displaced.setName(reservationName);
displaced.setPermissions(reservationRead, reservationWrite, false);
displaced.setComment(reservationComment);
if (reservationSource != null) displaced.setSourceName(reservationSource);
String reservationSpace = overlaySpaceName(reservationName, overlayName);
if (!reservationSpace.equals(overlayName)) currentProgram.renameOverlaySpace(overlayName, reservationSpace);
canonical.setName(codeName);
AddressSpace overlay = displaced.getStart().getAddressSpace();
// The reservation holds no code, so its labels mark no entry points. An entry mark the
// loader gave one of them stays at its default-space address (docs/providers/ghidra-riscv.md).
for (Label label : labels) {
symbols.createLabel(overlay.getAddress(label.offset()), label.name(), label.namespace(), label.source());
}
JsonObject outcome = new JsonObject();
outcome.add("code", echoCode(canonical, overlayName));
outcome.add("reservation", echo(displaced, space.getName()));
outcome.addProperty("functions", count(currentProgram.getFunctionManager().getFunctions(range(canonical), true)));
outcome.addProperty("entry_points", entryPoints(canonical).size());
outcome.addProperty("reservation_labels", count(symbols.getSymbols(range(displaced), SymbolType.LABEL, true)));
return outcome;
}
/**
* The overlay space name Ghidra 12.1.4's memory map derives from a block name, as for an
* overlay block it creates: `:` and characters up to space become `_`, and a name another
* address space has gains `.1`, `.2` and so on. Section names are display labels, so a
* reservation named like another address space, or with characters Ghidra rejects, still loads.
*/
private String overlaySpaceName(String blockName, String current) {
StringBuilder fixed = new StringBuilder(blockName.length());
for (char c : blockName.toCharArray()) fixed.append(c == ':' || c <= 0x20 ? '_' : c);
AddressFactory factory = currentProgram.getAddressFactory();
String name = fixed.toString();
for (int index = 1; !name.equals(current) && factory.getAddressSpace(name) != null; index++) {
name = fixed + "." + index;
}
return name;
}
/** A block as the script left it, for the client to compare with the committed section. */
private static JsonObject echo(MemoryBlock block, String spaceBefore) {
JsonObject result = new JsonObject();
result.addProperty("name", block.getName());
result.addProperty("address", hex(block.getStart().getOffset()));
result.addProperty("size", hex(block.getSize()));
result.addProperty("space_before", spaceBefore);
result.addProperty("space_after", block.getStart().getAddressSpace().getName());
return result;
}
private static JsonObject echoCode(MemoryBlock block, String spaceBefore) {
JsonObject result = echo(block, spaceBefore);
result.addProperty("file_offset", hex(block.getSourceInfos().get(0).getFileBytesOffset()));
return result;
}
private void report(String outcome, JsonObject counts) {
JsonObject result = new JsonObject();
result.addProperty("policy", POLICY);
result.addProperty("outcome", outcome);
if (counts != null) {
for (String key : counts.keySet()) result.add(key, counts.get(key));
}
currentProgram.getOptions(Program.PROGRAM_INFO).setString(REPORT_KEY, result.toString());
println("REA ELF load preparation: " + result);
}
/**
* Written instead of an outcome: REA refuses the session with this reason, so the program is
* not analyzed. Later scripts still run, and the bridge reports the refusal.
*/
private void refuse(String reason) throws ImproperUseException {
JsonObject result = new JsonObject();
result.addProperty("policy", POLICY);
result.addProperty("refused", reason);
currentProgram.getOptions(Program.PROGRAM_INFO).setString(REPORT_KEY, result.toString());
println("REA ELF load preparation refused: " + reason);
enableHeadlessAnalysis(false);
}
private static boolean mapsFile(MemoryBlock block, FileBytes file, long offset) {
List<MemoryBlockSourceInfo> sources = block.getSourceInfos();
if (sources.size() != 1) return false;
MemoryBlockSourceInfo source = sources.get(0);
return source.getFileBytes().map(file::equals).orElse(false) &&
source.getFileBytesOffset() == offset && source.getLength() == block.getSize();
}
private List<Address> entryPoints(MemoryBlock block) {
List<Address> found = new ArrayList<>();
AddressIterator entries = currentProgram.getSymbolTable().getExternalEntryPointIterator();
while (entries.hasNext()) {
Address entry = entries.next();
// An overlay block also contains its base space's addresses at the same offsets.
if (entry.getAddressSpace().equals(block.getStart().getAddressSpace()) && block.contains(entry)) {
found.add(entry);
}
}
return found;
}
private static int count(Iterable<?> values) {
int count = 0;
for (Object ignored : values) count++;
return count;
}
private static String detail(Exception failure) {
String text = failure.getClass().getSimpleName() +
(failure.getMessage() == null ? "" : ": " + failure.getMessage());
return text.length() <= FAILURE_DETAIL_MAX ? text : text.substring(0, FAILURE_DETAIL_MAX);
}
/**
* A name for a block that exists only during the move. Block names are unique in a program
* but carry no meaning here, so a section already named `<name>.rea` must not refuse the image.
* The final names stay free too: the reservation's block is gone when the code's temporary is
* named, and both blocks take their final names back after it.
*/
private String unusedBlockName(String base, String... finalNames) {
Memory memory = currentProgram.getMemory();
Set<String> reserved = Set.copyOf(List.of(finalNames));
String name = base + ".rea";
for (int index = 1; memory.getBlock(name) != null || reserved.contains(name); index++) {
name = base + ".rea." + index;
}
return name;
}
private static AddressSet range(MemoryBlock block) {
return new AddressSet(block.getStart(), block.getEnd());
}
private static long parseHex(String value) {
if (!value.matches("0x[0-9a-f]{1,16}")) {
throw new IllegalArgumentException("ELF load preparation expects lowercase 0x-hex values: " + value);
}
return Long.parseUnsignedLong(value.substring(2), 16);
}
private static String hex(long value) {
return "0x" + Long.toUnsignedString(value, 16);
}
}