diff --git a/lld/ELF/Writer.cpp b/lld/ELF/Writer.cpp --- a/lld/ELF/Writer.cpp +++ b/lld/ELF/Writer.cpp @@ -1355,11 +1355,22 @@ const DenseMap &order) { StringRef name = sec->name; + // Sort input sections by priority using the list provided + // by --symbol-ordering-file. + auto sortBySectionOrder = [&]() { + if (!order.empty()) + for (BaseCommand *b : sec->sectionCommands) + if (auto *isd = dyn_cast(b)) + sortISDBySectionOrder(isd, order); + }; + // Sort input sections by section name suffixes for // __attribute__((init_priority(N))). if (name == ".init_array" || name == ".fini_array") { - if (!script->hasSectionsCommand) + if (!script->hasSectionsCommand) { + sortBySectionOrder(); sec->sortInitFini(); + } return; } @@ -1392,12 +1403,7 @@ return; } - // Sort input sections by priority using the list provided - // by --symbol-ordering-file. - if (!order.empty()) - for (BaseCommand *b : sec->sectionCommands) - if (auto *isd = dyn_cast(b)) - sortISDBySectionOrder(isd, order); + sortBySectionOrder(); } // If no layout was provided by linker script, we want to apply default diff --git a/lld/test/ELF/shuffle-sections-init-fini.s b/lld/test/ELF/shuffle-sections-init-fini.s new file mode 100644 --- /dev/null +++ b/lld/test/ELF/shuffle-sections-init-fini.s @@ -0,0 +1,25 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64 %s -o %t.o + +# RUN: ld.lld --shuffle-sections=1 %t.o -o %t +# RUN: llvm-readelf -x .init_array -x .fini_array %t | FileCheck %s +# RUN: ld.lld --shuffle-sections=2 %t.o -o %t +# RUN: llvm-readelf -x .init_array -x .fini_array %t | FileCheck %s +# CHECK: Hex dump of section '.init_array' +# CHECK-NEXT: ff{{....}} +# CHECK: Hex dump of section '.fini_array' +# CHECK-NEXT: {{....}}ff + +.section .init_array,"aw",@init_array,unique,0 +.byte 0 +.section .init_array,"aw",@init_array,unique,1 +.byte 1 +.section .init_array.1,"aw",@init_array,unique,2 +.byte 255 + +.section .fini_array,"aw",@fini_array,unique,0 +.byte 0 +.section .fini_array,"aw",@fini_array,unique,1 +.byte 1 +.section .fini_array.1,"aw",@fini_array,unique,2 +.byte 255