From 9d6dab13d856ba0bc5c49ff656e8368b90e60d2e Mon Sep 17 00:00:00 2001 From: Rangi <35663410+Rangi42@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:40:15 -0400 Subject: [PATCH] Sort linked sections by alignment before size (#2201) Note that Libbet has no canonical hash and is sensitive to floating section placement --- src/link/assign.cpp | 16 +++++++++------- test/external/libbet.cfg | 2 +- test/link/section-sorting.asm | 5 +++++ test/link/section-sorting.out | 0 4 files changed, 15 insertions(+), 8 deletions(-) create mode 100644 test/link/section-sorting.asm create mode 100644 test/link/section-sorting.out diff --git a/src/link/assign.cpp b/src/link/assign.cpp index 0b985ece..2d55fdbe 100644 --- a/src/link/assign.cpp +++ b/src/link/assign.cpp @@ -416,14 +416,16 @@ static void categorizeSection(Section §ion) { constraints |= ALIGN_CONSTRAINED; } + // Insert section while keeping the list sorted by decreasing alignment and size std::deque
§ions = unassignedSections[constraints]; - - // Insert section while keeping the list sorted by decreasing size - auto pos = sections.begin(); - while (pos != sections.end() && (*pos)->size > section.size) { - ++pos; - } - sections.insert(pos, §ion); + auto const compareSections = [](Section const *prev, Section const §) { + assume(prev->isAlignFixed == sect.isAlignFixed); + if (sect.isAlignFixed && prev->alignMask != sect.alignMask) { + return prev->alignMask > sect.alignMask; + } + return prev->size > sect.size; + }; + sections.insert(std::lower_bound(RANGE(sections), section, compareSections), §ion); } static void checkOverlayCompat() { diff --git a/test/external/libbet.cfg b/test/external/libbet.cfg index 755de715..65ba1630 100644 --- a/test/external/libbet.cfg +++ b/test/external/libbet.cfg @@ -6,4 +6,4 @@ EXT_TEST_IS_NONFREE=false EXT_TEST_TARGET=all EXT_TEST_FILE=libbet.gb -EXT_TEST_HASH=f117089aa056600e2d404bbcbac96b016fc64611 +EXT_TEST_HASH=c438995f6099f3736517f3f1bffc006b5fe458c4 diff --git a/test/link/section-sorting.asm b/test/link/section-sorting.asm new file mode 100644 index 00000000..2a91617d --- /dev/null +++ b/test/link/section-sorting.asm @@ -0,0 +1,5 @@ +SECTION "One byte", ROM0,ALIGN[14] + db + +SECTION "Two bytes", ROM0,ALIGN[13] + dw diff --git a/test/link/section-sorting.out b/test/link/section-sorting.out new file mode 100644 index 00000000..e69de29b