Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ endif

LDFLAGS := -EL -maarch64elf --no-undefined -X -Bsymbolic \
-z notext --no-apply-dynamic-relocs --orphan-handling=warn \
-z nocopyreloc --gc-sections -pie
-z nocopyreloc -z pack-relative-relocs --gc-sections -pie

MINILZLIB_OBJECTS := $(patsubst %,minilzlib/%, \
dictbuf.o inputbuf.o lzma2dec.o lzmadec.o rangedec.o xzstream.o)
Expand Down
17 changes: 15 additions & 2 deletions aura-raw.ld
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ SECTIONS {
_init_content_end = .; /* tools/stage1_room.py */
} :text
/*
* .init, .text, .rodata and .rela.dyn follow each other with no step between them: memory.c
* maps [_base, _rodata_end) RX as one region and smp.c cleans it as one range, so a step only
* .init, .text, .rodata and the relocations follow each other with no step between them:
* memory.c maps [_base, _rodata_end) RX as one region and smp.c cleans it as one range, so a step only
* left part of a slot unused and made code move between slots by hand to fit.
*/
.text : {
Expand Down Expand Up @@ -79,6 +79,19 @@ SECTIONS {
/* The load header's footprint (start.S) leaves an R_AARCH64_NONE here; keep it inside the
* padding and out of the range apply_rela() walks, which only accepts relative entries. */
*(.rela.init)
} :text
/*
* The relative relocations of aligned pointers, packed (-z pack-relative-relocs): an address
* entry relocates one word, a bitmap entry up to 63 words after it, and each word holds its
* link-time value (base 0) in the file. Stored as one 24-byte .rela.dyn entry per pointer
* they took about 74 KiB of the ESP Stage 2 and pushed it close to _file_limit; packed they
* take about 10 KiB. apply_relr() (startup.c) applies them after apply_rela(), once per run;
* .rela.dyn keeps the relocations a linker does not pack (unaligned words).
*/
.relr.dyn : {
_relr_start = .;
*(.relr.dyn)
_relr_end = .;
_rodata_content_end = .;
. = ALIGN(_layout_step);
} :text
Expand Down
6 changes: 6 additions & 0 deletions aura.ld
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,12 @@ SECTIONS {
/* The load header's footprint (start.S) leaves an R_AARCH64_NONE here; keep it inside the
* padding and out of the range apply_rela() walks, which only accepts relative entries. */
*(.rela.init)
} :rodata
/* The packed relative relocations (-z pack-relative-relocs, see aura-raw.ld). */
.relr.dyn : {
_relr_start = .;
*(.relr.dyn)
_relr_end = .;
. = ALIGN(0x10000);
} :rodata
_rodata_end = .;
Expand Down
23 changes: 13 additions & 10 deletions proxyclient/aura/loadobjs.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,21 @@ def _load_base_symbols(self):

addrs = self._load_elf_symbols(self.base_object, self.u.proxy.get_base())

# sanity check: compare the .rela table between ELF and aura image on target
rela_base = addrs["_rela_start"]
rela_length = addrs["_rela_end"] - rela_base
rela_target = self.u.iface.readmem(rela_base, rela_length)

tmp = os.path.join(tempfile.mkdtemp(), "bin")
# sanity check: compare the relocation tables (.rela.dyn, and .relr.dyn where the image
# has one) between ELF and aura image on target
path = os.path.join(self.SOURCE_ROOT, self.base_object)
run_tool(_toolchain.OBJCOPY, "-O", "binary", path, tmp, "--only-section=.rela.dyn")
rela_objfile = open(tmp, "rb").read()
for section, start, end in ((".rela.dyn", "_rela_start", "_rela_end"),
(".relr.dyn", "_relr_start", "_relr_end")):
if start not in addrs:
continue
table_target = self.u.iface.readmem(addrs[start], addrs[end] - addrs[start])

tmp = os.path.join(tempfile.mkdtemp(), "bin")
run_tool(_toolchain.OBJCOPY, "-O", "binary", path, tmp, f"--only-section={section}")
table_objfile = open(tmp, "rb").read()

if rela_objfile[:len(rela_target)] != rela_target:
raise Exception(f"Mismatch between {self.base_object} and image on target")
if table_objfile[:len(table_target)] != table_target:
raise Exception(f"Mismatch between {self.base_object} and image on target")

def aura_is_macho(self):
p = self.u.proxy
Expand Down
6 changes: 6 additions & 0 deletions src/start.S
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,12 @@ _start:
adrp x2, _rela_end
add x2, x2, :lo12:_rela_end
bl apply_rela
mov x0, x20
adrp x1, _relr_start
add x1, x1, :lo12:_relr_start
adrp x2, _relr_end
add x2, x2, :lo12:_relr_end
bl apply_relr

mov w0, '1'
bl debug_putc
Expand Down
26 changes: 26 additions & 0 deletions src/startup.c
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,32 @@ void apply_rela(uint64_t base, struct rela_entry *rela_start, struct rela_entry
}
}

/*
* The packed relative relocations (SHT_RELR, aura-raw.ld). An even entry is the offset of a word
* to relocate; an odd one is a bitmap whose bits 1 to 63 select, in order, which of the 63 words
* from where the previous entry left off to relocate. Each word holds its link-time value, so the
* base is added once: start.S calls this once, after the image has moved to where it runs. Like
* apply_rela() it runs before the image is relocated, so it touches no globals.
*/
void apply_relr(uint64_t base, const uint64_t *relr_start, const uint64_t *relr_end)
{
uint64_t *where = NULL;

for (const uint64_t *e = relr_start; e < relr_end; e++) {
if (!(*e & 1)) {
where = (uint64_t *)(base + *e);
*where++ += base;
continue;
}
uint64_t *word = where;
for (uint64_t bits = *e >> 1; bits; bits >>= 1, word++) {
if (bits & 1)
*word += base;
}
where += 63;
}
}

extern uint32_t _v_sp0_sync[], _v_sp0_irq[], _v_sp0_fiq[], _v_sp0_serr[];
#ifdef SPTM_VIRT
extern uint32_t _v_lower_sync[]; /* nv2_asm.S */
Expand Down
29 changes: 21 additions & 8 deletions tests/python/test_rela_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
moved .data, .bss and the stacks up by 64 KiB. The image here carries the same kind of entry plus
one relative relocation and is linked with the Makefile's LDFLAGS, using each available AArch64
linker. The checks: no orphan warning, only R_AARCH64_RELATIVE entries in [_rela_start, _rela_end)
(apply_rela() accepts nothing else), and nothing past the padding, so _rodata_end is still the
step boundary after _rela_end (_layout_step in aura-raw.ld, 64 KiB in aura.ld). With GNU ld, a control link without the script's .rela.init line
must show the old layout.
(apply_rela() accepts nothing else; the unaligned pointer stays there), the aligned pointers packed
in [_relr_start, _relr_end) (-z pack-relative-relocs, apply_relr()), and nothing past the padding,
so _rodata_end is still the step boundary after _relr_end (_layout_step in aura-raw.ld, 64 KiB in
aura.ld). With GNU ld, a control link without the script's .rela.init line must warn of the orphan.
"""
import platform
import re
Expand Down Expand Up @@ -42,6 +43,10 @@
.balign 8
ptr:
.quad _start
.quad _start + 8
.byte 0
unaligned:
.quad _start + 16
'''


Expand Down Expand Up @@ -98,11 +103,18 @@ def layout(tmp_path, linker, script, name):
sections = subprocess.run([READELF, "-S", "-W", str(elf)], check=True, capture_output=True, text=True).stdout
match = re.search(r"\] \.rela\.dyn\s+\S+\s+([0-9a-f]+)\s+[0-9a-f]+\s+([0-9a-f]+)", sections)
vma, size = int(match.group(1), 16), int(match.group(2), 16)
# The packed relocations follow .rela.dyn and end the read-execute region (-z
# pack-relative-relocs): the aligned pointers are there, the unaligned one stays in .rela.dyn.
relr = re.search(r"\] \.relr\.dyn\s+\S+\s+([0-9a-f]+)\s+[0-9a-f]+\s+([0-9a-f]+)", sections)
assert relr, sections
relr_vma, relr_size = int(relr.group(1), 16), int(relr.group(2), 16)
assert relr_vma >= vma + size and sym["_relr_end"] - sym["_relr_start"] > 0
assert relr_vma <= sym["_relr_start"] and sym["_relr_end"] <= relr_vma + relr_size
raw = tmp_path / f"{name}.rela"
subprocess.run([OBJCOPY, "-O", "binary", "--only-section=.rela.dyn", str(elf), str(raw)], check=True)
data = raw.read_bytes()[sym["_rela_start"] - vma:sym["_rela_end"] - vma]
types = [struct.unpack_from("<QQq", data, off)[1] & 0xFFFFFFFF for off in range(0, len(data), 24)]
return sym, vma + size, types, result.stderr
return sym, max(vma + size, relr_vma + relr_size), types, result.stderr


@pytest.mark.skipif(not (NM and READELF and OBJCOPY), reason="needs nm, readelf and objcopy")
Expand All @@ -116,16 +128,17 @@ def test_rela_init_stays_inside_rela_dyn_padding(tmp_path, kind, script):
assert "orphan" not in warnings, warnings
assert types and all(t == R_AARCH64_RELATIVE for t in types), types
step = sym.get("_layout_step", 0x10000)
boundary = (sym["_rela_end"] + step - 1) & ~(step - 1)
assert end == boundary == sym["_rodata_end"], (hex(sym["_rela_end"]), hex(end), hex(sym["_rodata_end"]))
boundary = (sym["_relr_end"] + step - 1) & ~(step - 1)
assert end == boundary == sym["_rodata_end"], (hex(sym["_relr_end"]), hex(end), hex(sym["_rodata_end"]))

if kind != "gnu":
return
# Control: without the .rela.init line, GNU ld places the piece after the padding, as it did.
# Control: without the .rela.init line, GNU ld places the piece as an orphan. Before the packed
# relocations it went after the padding and moved .data up a step; it now lands between
# .rela.dyn and .relr.dyn, but the line keeps it listed (--orphan-handling=warn).
text = (REPO / script).read_text()
assert text.count(FIX_LINE) == 1
unlisted = tmp_path / script
unlisted.write_text(text.replace(FIX_LINE, ""))
sym, end, types, warnings = layout(tmp_path, linker, unlisted, "control")
assert "orphan section `.rela.init'" in warnings, warnings
assert sym["_rodata_end"] == end > ((sym["_rela_end"] + step - 1) & ~(step - 1))
196 changes: 196 additions & 0 deletions tests/python/test_relr_apply.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# SPDX-License-Identifier: MIT
"""Apply an image's packed relative relocations with the production apply_rela()/apply_relr().

The image is linked twice with aura-raw.ld and each available AArch64 linker: with the Makefile's
LDFLAGS (-z pack-relative-relocs: aligned pointers in .relr.dyn, holding their link-time value)
and, as the reference, without packing (one .rela.dyn entry per pointer). Its pointers cover the
three kinds of entry: a run long enough to need two bitmap entries after its address entry,
pointers more than 63 words apart (address entries only), a gap inside one bitmap, and one
unaligned pointer that stays in .rela.dyn. The packed image is copied to a buffer at a nonzero
base and relocated the way start.S does it (apply_rela, then apply_relr), natively on the host;
every word the reference relocates must then hold base + addend, and no other byte may change.
"""
import re
import struct
import subprocess

import pytest

import test_rela_layout
from test_rela_layout import LINKERS, NM, OBJCOPY, READELF, ldflags
from test_smp_timeouts import REPO, compile_and_run

IMAGE = r'''
.section .init, "ax"
.globl _start
_start:
adrp x0, run
adrp x0, target
b 1f
.quad _image_footprint
1:
ret
.section .text, "ax"
target:
ret
.section .rodata, "a"
.ascii "rodata"
.section .data, "aw"
.balign 8
run:
.rept 140
.quad target + (. - run)
.endr
.quad 0x1234
sparse:
.quad run
.rept 100
.quad 0x5555
.endr
.quad sparse
.quad 0x6666
.quad target + 0x40
.rept 5
.quad 0x7777
.endr
.quad target + 0x80
.byte 0xaa
unaligned:
.quad target + 0x100
.byte 0xbb
'''


def assemble(tmp_path):
# test_rela_layout's assembler choice, with this image.
saved, test_rela_layout.IMAGE = test_rela_layout.IMAGE, IMAGE
try:
return test_rela_layout.assemble(tmp_path)
finally:
test_rela_layout.IMAGE = saved


def symbols(elf):
sym = {}
for line in subprocess.run([NM, str(elf)], check=True, capture_output=True, text=True).stdout.splitlines():
fields = line.split()
if len(fields) == 3:
sym[fields[2]] = int(fields[0], 16)
return sym


def link(tmp_path, linker, name, flags):
obj = assemble(tmp_path)
elf = tmp_path / f"{name}.elf"
result = subprocess.run([linker, "-T", str(REPO / "aura-raw.ld"), *flags, "-o", str(elf), str(obj)],
cwd=REPO, capture_output=True, text=True)
assert result.returncode == 0, result.stderr
return elf


def section(elf, name):
out = subprocess.run([READELF, "-S", "-W", str(elf)], check=True, capture_output=True, text=True).stdout
match = re.search(r"\] " + re.escape(name) + r"\s+\S+\s+([0-9a-f]+)\s+[0-9a-f]+\s+([0-9a-f]+)", out)
return (int(match.group(1), 16), int(match.group(2), 16)) if match else (0, 0)


def raw(tmp_path, elf, name, only=None):
out = tmp_path / f"{name}.bin"
subprocess.run([OBJCOPY, "-O", "binary", *([f"--only-section={only}"] if only else []), str(elf), str(out)],
check=True)
return out.read_bytes()


def reference(tmp_path, linker):
"""offset -> addend of every relative relocation, from the unpacked link."""
packed = ldflags()
at = packed.index("pack-relative-relocs")
assert packed[at - 1] == "-z"
flags = packed[:at - 1] + packed[at + 1:]
elf = link(tmp_path, linker, "unpacked", flags)
sym = symbols(elf)
assert sym["_relr_end"] == sym["_relr_start"]
vma, _ = section(elf, ".rela.dyn")
data = raw(tmp_path, elf, "unpacked-rela", ".rela.dyn")[sym["_rela_start"] - vma:sym["_rela_end"] - vma]
entries = [struct.unpack_from("<QQq", data, off) for off in range(0, len(data), 24)]
assert all(info & 0xFFFFFFFF == 1027 for _, info, _ in entries)
return {off: addend for off, _, addend in entries}, sym


def production():
source = (REPO / "src/startup.c").read_text()
struct_def = source[source.index("struct rela_entry {"):source.index("};", source.index("struct rela_entry {")) + 2]
start = source.index("#define R_AARCH64_RELATIVE")
end = source.index("extern uint32_t _v_sp0_sync[]")
return struct_def + "\n" + source[start:end]


@pytest.mark.skipif(not (NM and READELF and OBJCOPY), reason="needs nm, readelf and objcopy")
@pytest.mark.parametrize("kind", ["gnu", "lld"])
def test_apply_relr_matches_unpacked_relocations(tmp_path, kind):
linker = LINKERS[kind]
if not linker:
pytest.skip(f"no {kind} AArch64 linker")
expected, ref_sym = reference(tmp_path, linker)
# 140 run words + sparse pointers + bitmap-gap pointers + the unaligned one.
assert len(expected) == 140 + 2 + 2 + 1, len(expected)

elf = link(tmp_path, linker, "packed", ldflags())
sym = symbols(elf)
assert {k: sym[k] for k in ("run", "sparse", "unaligned")} == \
{k: ref_sym[k] for k in ("run", "sparse", "unaligned")}
relr_count = (sym["_relr_end"] - sym["_relr_start"]) // 8
rela_count = (sym["_rela_end"] - sym["_rela_start"]) // 24
# Packed: the unaligned pointer alone stays a RELA entry; 144 aligned words take a handful
# of RELR entries (address + bitmaps), not 144.
assert rela_count == 1 and 3 <= relr_count <= 8, (rela_count, relr_count)
image = raw(tmp_path, elf, "packed")
assert len(image) >= sym["unaligned"] + 8

base = 0x40000000
words = ",".join(f"{{{off:#x}u, {addend:#x}u}}" for off, addend in sorted(expected.items()))
harness = r'''
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef uint64_t u64;
static void debug_putc(char c) { (void)c; abort(); }
''' + production() + r'''
static const unsigned char file[] = {''' + ",".join(str(b) for b in image) + r'''};
static const struct { uint64_t off, addend; } expected[] = {''' + words + r'''};
#define BASE ''' + f"{base:#x}" + r'''ULL
int main(void)
{
/* Run the image at BASE: the buffer holds it at its offsets, and the relocations write
BASE + addend; the buffer's own address is added back for the host. */
unsigned char *mem = aligned_alloc(0x4000, (sizeof(file) + 0x3fff) & ~0x3fffUL);
assert(mem);
memcpy(mem, file, sizeof(file));
uint64_t host = (uint64_t)mem;
apply_rela(host, (struct rela_entry *)(mem + ''' + f"{sym['_rela_start']:#x}" + r'''),
(struct rela_entry *)(mem + ''' + f"{sym['_rela_end']:#x}" + r'''));
apply_relr(host, (const uint64_t *)(mem + ''' + f"{sym['_relr_start']:#x}" + r'''),
(const uint64_t *)(mem + ''' + f"{sym['_relr_end']:#x}" + r'''));
unsigned char *touched = calloc(1, sizeof(file));
for (size_t i = 0; i < sizeof(expected) / sizeof(expected[0]); i++) {
uint64_t value;
memcpy(&value, mem + expected[i].off, 8);
if (value != host + expected[i].addend) {
fprintf(stderr, "word %#llx: %#llx, want %#llx\n", (unsigned long long)expected[i].off,
(unsigned long long)(value - host), (unsigned long long)expected[i].addend);
return 1;
}
memset(touched + expected[i].off, 1, 8);
}
for (size_t i = 0; i < sizeof(file); i++)
if (!touched[i] && mem[i] != file[i]) {
fprintf(stderr, "byte %#zx changed\n", i);
return 1;
}
(void)BASE;
return 0;
}
'''
compile_and_run(tmp_path, f"relr-{kind}", harness)
Loading
Loading