From 06b3413961246fd41db99a0edfd5ce9ad085921a Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Mon, 28 Sep 2026 14:22:48 +1300 Subject: [PATCH] fix(relinker): align the linux header load segment to the largest segment alignment Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01ButHENCbXXt8h4EZuWUabJ --- core/relinker/CMakeLists.txt | 2 + .../general/ProgramHeaderLayoutBuilder.cpp | 6 +- .../tests/test_linux_load_alignment.py | 56 +++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 core/relinker/relinker/tests/test_linux_load_alignment.py diff --git a/core/relinker/CMakeLists.txt b/core/relinker/CMakeLists.txt index 42ebb17ba..f8a4a4a09 100644 --- a/core/relinker/CMakeLists.txt +++ b/core/relinker/CMakeLists.txt @@ -140,6 +140,8 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_empty_tls.py $) add_test(NAME tls_function_coverage COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_tls_function_coverage.py $) + add_test(NAME linux_load_alignment COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_linux_load_alignment.py $) else() message(STATUS "Python3 interpreter not found; skipping Python relinker tests") endif() diff --git a/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp b/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp index 36245adee..b12f1ad90 100644 --- a/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp +++ b/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp @@ -144,7 +144,11 @@ std::uint16_t ProgramHeaderLayoutBuilder::WriteLayout( ", available " + std::to_string(request.PhNum)); const std::uint64_t headerBlockSize = request.PhOff + static_cast(neededPh) * request.PhEntSize; - const std::uint64_t headerBlockAlign = kDefaultLoadAlignment; + std::uint64_t headerBlockAlign = kDefaultLoadAlignment; + for (const auto& ph : request.OriginalHeaders) { + if (ph.Type == PT_LOAD && !_segmentFilter->ShouldSkip(ph) && ph.Alignment > headerBlockAlign && (ph.Alignment & (ph.Alignment - 1)) == 0) + headerBlockAlign = ph.Alignment; + } const std::uint64_t headerBlockVaddr = (request.ExtraBlockVaddr + request.ExtraBlockSize + headerBlockAlign - 1) & ~(headerBlockAlign - 1); diff --git a/core/relinker/relinker/tests/test_linux_load_alignment.py b/core/relinker/relinker/tests/test_linux_load_alignment.py new file mode 100644 index 000000000..2e2d8afaf --- /dev/null +++ b/core/relinker/relinker/tests/test_linux_load_alignment.py @@ -0,0 +1,56 @@ +"""Check that a Linux relink keeps the image base aligned to the guest segment alignment.""" + +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +PT_LOAD = 1 +PT_SCE_VERSION = 0x6FFFFF01 + + +def fixture(): + image = bytearray(0x8000) + image[:16] = b"\x7fELF\x02\x01\x01" + bytes(9) + struct.pack_into("