Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 12 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,18 @@ LDFLAGS := -EL -maarch64elf --no-undefined -X -Bsymbolic \
-z notext --no-apply-dynamic-relocs --orphan-handling=warn \
-z nocopyreloc --gc-sections -pie

# Pack the relative relocations as RELR (.relr.dyn, applied by apply_relr() in startup.c): 8 bytes
# per run of up to 63 words instead of 24 bytes per word in .rela.dyn, which sits in the file part
# below _file_limit (aura-raw.ld). Only if the linker can (LLD 15 and later, a GNU ld with AArch64
# DT_RELR support); with an older one every relocation stays in .rela.dyn for apply_rela(). The
# probe links a one-symbol object with --fatal-warnings, as some linkers only warn about a -z
# value they do not know.
LD_RELR := $(shell t=$$(mktemp -d) && \
printf '.globl _start\n_start:\n' | $(AS) -c -x assembler - -o $$t/p.o 2>/dev/null && \
$(LD) -EL -maarch64elf -pie -z pack-relative-relocs --fatal-warnings -o $$t/p $$t/p.o \
>/dev/null 2>&1 && echo -z pack-relative-relocs; rm -rf $$t)
LDFLAGS += $(LD_RELR)

MINILZLIB_OBJECTS := $(patsubst %,minilzlib/%, \
dictbuf.o inputbuf.o lzma2dec.o lzmadec.o rangedec.o xzstream.o)

Expand Down
9 changes: 9 additions & 0 deletions aura-raw.ld
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ SECTIONS {
*(.rodata.*)
. = ALIGN(8);
} :rodata
/*
* The relative relocations, packed as RELR when the linker can (Makefile LD_RELR) and
* applied by apply_relr() (startup.c). Anything left unpacked stays in .rela.dyn below.
*/
.relr.dyn : {
_relr_start = .;
*(.relr.dyn)
_relr_end = .;
} :rodata
.rela.dyn : {
_rela_start = .;
*(.rela)
Expand Down
9 changes: 9 additions & 0 deletions aura.ld
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,15 @@ SECTIONS {
*(.rodata.*)
. = ALIGN(8);
} :rodata
/*
* The relative relocations, packed as RELR when the linker can (Makefile LD_RELR) and
* applied by apply_relr() (startup.c). Anything left unpacked stays in .rela.dyn below.
*/
.relr.dyn : {
_relr_start = .;
*(.relr.dyn)
_relr_end = .;
} :rodata
.rela.dyn : {
_rela_start = .;
*(.rela)
Expand Down
30 changes: 18 additions & 12 deletions proxyclient/aura/loadobjs.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,24 @@ 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")
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()

if rela_objfile[:len(rela_target)] != rela_target:
raise Exception(f"Mismatch between {self.base_object} and image on target")
# sanity check: compare the relocation tables between ELF and aura image on target
# (apply_relr() and apply_rela() only read them, so they match the file)
for section, start, end in ((".relr.dyn", "_relr_start", "_relr_end"),
(".rela.dyn", "_rela_start", "_rela_end")):
if start not in addrs:
continue
length = addrs[end] - addrs[start]
if not length:
continue
table_target = self.u.iface.readmem(addrs[start], length)

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

if table_objfile[:length] != 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
5 changes: 4 additions & 1 deletion proxyclient/tools/validate_legacy_boot.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ def __init__(self, binary, chip, part, features=True, poll_failure=False):
if addr not in pages:
self.uc.mem_map(addr, 4096); pages.add(addr)
self.uc.mem_write(s['p_vaddr'], s.data())
for relocation in binary.elf.get_section_by_name('.rela.dyn').iter_relocations():
# The image runs at its link address (0), so a RELR-packed word already holds its value;
# only .rela.dyn words (zero in the file, --no-apply-dynamic-relocs) need their addend.
rela = binary.elf.get_section_by_name('.rela.dyn')
for relocation in rela.iter_relocations() if rela else ():
if relocation['r_info_type'] == 0:
continue
assert relocation['r_info_type'] == 1027
Expand Down
7 changes: 7 additions & 0 deletions src/start.S
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,13 @@ _start:

adrp x0, _base
mov x20, x0
adrp x1, _relr_start
add x1, x1, :lo12:_relr_start
adrp x2, _relr_end
add x2, x2, :lo12:_relr_end
bl apply_relr

mov x0, x20
adrp x1, _rela_start
add x1, x1, :lo12:_rela_start
adrp x2, _rela_end
Expand Down
27 changes: 27 additions & 0 deletions src/startup.c
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,33 @@ void apply_rela(uint64_t base, struct rela_entry *rela_start, struct rela_entry
}
}

/*
* The relative relocations packed as RELR (-z pack-relative-relocs, Makefile): an even entry is
* the offset of a word to relocate, an odd entry a bitmap of the 63 words after the last one
* relocated (bit n + 1 for word n). Unlike a RELA entry, the word already holds its link-time
* value, so it is relocated by adding base: this runs once per image, from start.S at _start
* after any copy of the image, before the copy is used. CPU resets enter at cpu_reset and do
* not come here again.
*/
void apply_relr(uint64_t base, const uint64_t *relr_start, const uint64_t *relr_end)
{
u64 *where = NULL;

for (const uint64_t *e = relr_start; e < relr_end; e++) {
if (!(*e & 1)) {
where = (u64 *)(base + *e);
*where++ += base;
} else {
u64 *p = where;

for (uint64_t bits = *e >> 1; bits; bits >>= 1, p++)
if (bits & 1)
*p += 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
6 changes: 3 additions & 3 deletions tests/python/test_rela_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def gnu_ld():
OBJCOPY = tool("llvm-objcopy", "aarch64-linux-gnu-objcopy", "objcopy")


def assemble(tmp_path):
obj = tmp_path / "image.o"
def assemble(tmp_path, source=IMAGE, name="image"):
obj = tmp_path / f"{name}.o"
clang = shutil.which("clang")
if clang:
cmd = [clang, "--target=aarch64-linux-gnu", "-c", "-x", "assembler", "-", "-o", str(obj)]
Expand All @@ -73,7 +73,7 @@ def assemble(tmp_path):
if not gcc:
pytest.skip("needs an AArch64 assembler")
cmd = [gcc, "-c", "-x", "assembler", "-", "-o", str(obj)]
subprocess.run(cmd, input=IMAGE, text=True, check=True)
subprocess.run(cmd, input=source, text=True, check=True)
return obj


Expand Down
189 changes: 189 additions & 0 deletions tests/python/test_relr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
# SPDX-License-Identifier: MIT
"""Check that RELR-packed relocations relocate an image exactly as the RELA table did.

The Makefile links with -z pack-relative-relocs when the linker can (LD_RELR). The relative
relocations then go to .relr.dyn, which start.S hands to apply_relr() (startup.c), and only what
the linker could not pack stays in .rela.dyn for apply_rela(). A RELR word already holds its
link-time value and is relocated by adding the base; a RELA word is set to base + addend. Here a
small image with runs of pointers, gaps longer than one 63-word bitmap, a pointer in .text and one
in .rodata is linked with the real linker scripts twice, with the Makefile's LDFLAGS and with
-z pack-relative-relocs added, using each available AArch64 linker. Both links are relocated at a
non-zero base and must give the same image. apply_relr() itself is compiled for the host and run
on the packed table.
"""
import re
import shutil
import struct
import subprocess

import pytest

from test_rela_layout import LINKERS, NM, OBJCOPY, READELF, R_AARCH64_RELATIVE, assemble, ldflags
from test_smp_timeouts import REPO

BASE = 0x8_0004_0000
RELR = ["-z", "pack-relative-relocs"]

IMAGE = r'''
.section .init, "ax"
.globl _start
_start:
adrp x0, table
ldr x0, [x0, :lo12:table]
adrp x1, text_pointer
adrp x2, rodata_pointer
b 1f
.quad _image_footprint
1:
ret
.section .text, "ax"
ret
.balign 8
text_pointer:
.quad table + 16
.section .rodata, "a"
.balign 8
rodata_pointer:
.quad _start + 4
.section .data, "aw"
.balign 8
table:
.rept 70
.quad _start
.endr
.quad 0x1234
.rept 5
.quad table + 8
.quad 0
.endr
.skip 8 * 100
.quad table
.skip 8 * 62
.quad .
'''


def relr_locations(table):
"""The words a RELR table names, decoded as apply_relr() walks it."""
locations, where = [], None
for (entry,) in struct.iter_unpack("<Q", table):
if not entry & 1:
locations.append(entry)
where = entry + 8
else:
locations += [where + 8 * bit for bit in range(63) if entry >> (bit + 1) & 1]
where += 63 * 8
return locations


def link(tmp_path, linker, script, name, extra):
obj = assemble(tmp_path, IMAGE)
elf = tmp_path / f"{name}.elf"
result = subprocess.run([linker, "-T", str(script), *ldflags(), *extra, "-o", str(elf), str(obj)],
cwd=REPO, capture_output=True, text=True)
assert result.returncode == 0, result.stderr
assert "orphan" not in result.stderr, result.stderr
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)
raw = tmp_path / f"{name}.bin"
subprocess.run([OBJCOPY, "-O", "binary", str(elf), str(raw)], check=True)
sections = subprocess.run([READELF, "-S", "-W", str(elf)], check=True, capture_output=True, text=True).stdout
return sym, bytearray(raw.read_bytes()), sections


def apply_rela(sym, image, base):
relocated = set()
for off in range(sym["_rela_start"], sym["_rela_end"], 24):
where, info, addend = struct.unpack_from("<QQq", image, off)
assert info & 0xFFFFFFFF == R_AARCH64_RELATIVE
struct.pack_into("<Q", image, where, base + addend)
relocated.add(where)
return relocated


@pytest.mark.skipif(not (NM and READELF and OBJCOPY), reason="needs nm, readelf and objcopy")
@pytest.mark.parametrize("script", ["aura-raw.ld", "aura.ld"])
@pytest.mark.parametrize("kind", ["gnu", "lld"])
def test_relr_relocates_like_rela(tmp_path, kind, script):
linker = LINKERS[kind]
if not linker:
pytest.skip(f"no {kind} AArch64 linker")
probe = subprocess.run([linker, "-EL", "-maarch64elf", "-pie", *RELR, "--fatal-warnings", "-o",
str(tmp_path / "probe"), str(assemble(tmp_path, ".globl _start\n_start:\n", "probe"))],
capture_output=True, text=True)
if probe.returncode:
pytest.skip(f"{linker} cannot pack relocations: {probe.stderr.strip()}")

rela_sym, rela_image, _ = link(tmp_path, linker, REPO / script, "rela", [])
relr_sym, relr_image, sections = link(tmp_path, linker, REPO / script, "relr", RELR)

# Every relative relocation is packed, into the section the script names, with no new step.
assert re.search(r"\] \.relr\.dyn\s", sections), sections
assert relr_sym["_rela_start"] == relr_sym["_rela_end"]
assert relr_sym["_relr_end"] > relr_sym["_relr_start"] == rela_sym["_relr_start"]
for name in ("_rodata_end", "_data_start", "_end"):
assert relr_sym[name] == rela_sym[name], name

relocated = apply_rela(rela_sym, rela_image, BASE)
assert len(relocated) == 70 + 5 + 4
table = bytes(relr_image[relr_sym["_relr_start"]:relr_sym["_relr_end"]])
locations = relr_locations(table)
assert sorted(locations) == sorted(relocated)
for where in locations:
(value,) = struct.unpack_from("<Q", relr_image, where)
struct.pack_into("<Q", relr_image, where, value + BASE)

# The relocated images are the same, apart from the relocation tables themselves.
tables = slice(rela_sym["_relr_start"], rela_sym["_rodata_end"])
rela_image[tables] = relr_image[tables] = b""
assert relr_image == rela_image

# startup.c's apply_relr(), built for the host, relocates the packed table the same way.
cc = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not cc:
return
source = (REPO / "src" / "startup.c").read_text()
function = re.search(r"^void apply_relr\(.*?^\}\n", source, re.S | re.M).group(0)
harness = tmp_path / "relr.c"
harness.write_text("""#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef uint64_t u64;
""" + function + """
/* relr IMAGE TABLE OUT: relocate IMAGE at the address it was read to, print that address */
int main(int argc, char **argv)
{
static u64 image[1 << 16], table[1 << 10];
FILE *f = fopen(argv[1], "rb");
size_t n = fread(image, 1, sizeof(image), f);
fclose(f);
f = fopen(argv[2], "rb");
size_t t = fread(table, 1, sizeof(table), f) / 8;
fclose(f);
apply_relr((uint64_t)image, table, table + t);
f = fopen(argv[3], "wb");
fwrite(image, 1, n, f);
fclose(f);
printf("%llx\\n", (unsigned long long)(uint64_t)image);
return 0;
}
""")
exe = tmp_path / "relr"
subprocess.run([cc, "-O2", "-Wall", "-Werror", "-o", str(exe), str(harness)], check=True)
_, packed, _ = link(tmp_path, linker, REPO / script, "packed", RELR)
assert len(packed) <= 8 << 16 and len(table) <= 8 << 10
(tmp_path / "packed.bin").write_bytes(packed)
(tmp_path / "table.bin").write_bytes(table)
host = int(subprocess.run([str(exe), str(tmp_path / "packed.bin"), str(tmp_path / "table.bin"),
str(tmp_path / "out.bin")], check=True, capture_output=True,
text=True).stdout, 16)
out = (tmp_path / "out.bin").read_bytes()
expected = bytearray(packed)
for where in locations:
(value,) = struct.unpack_from("<Q", expected, where)
struct.pack_into("<Q", expected, where, value + host)
assert out == expected
8 changes: 4 additions & 4 deletions tools/stage1_room.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
# SPDX-License-Identifier: MIT
"""How much a Stage 1 image can still grow before it reaches the DCP log buffer.

aura-raw.ld puts the code (.init and .text), .rodata + .rela.dyn and .data on 64 KiB steps, and
everything up to _file_vital_end must end below _file_limit (0x120000, see aura-raw.ld). The link
fails once it does not. This reports how close a build is, so a change or a toolchain that eats
the last few KiB fails in CI before a distribution's toolchain trips over it:
aura-raw.ld puts the code (.init and .text), .rodata + .relr.dyn + .rela.dyn and .data on 64 KiB
steps, and everything up to _file_vital_end must end below _file_limit (0x120000, see
aura-raw.ld). The link fails once it does not. This reports how close a build is, so a change or a
toolchain that eats the last few KiB fails in CI before a distribution's toolchain trips over it:

data bytes .data can grow before _file_vital_end reaches the limit
text/rodata
Expand Down
Loading