[lld] [LLD][COFF] Add support for custom section layout (PR #152779)

Martin Storsjö via llvm-commits llvm-commits at lists.llvm.org
Fri Aug 29 01:21:03 PDT 2025


================
@@ -1413,6 +1415,30 @@ void Writer::removeUnusedSections() {
   llvm::erase_if(ctx.outputSections, isUnused);
 }
 
+void Writer::layoutSections() {
+  llvm::TimeTraceScope timeScope("Layout sections");
+  if (ctx.config.sectionOrder.empty())
+    return;
+
+  std::unordered_map<const OutputSection *, size_t> originalOrder;
+  for (size_t i = 0; i < ctx.outputSections.size(); ++i)
+    originalOrder[ctx.outputSections[i]] = i;
+
+  llvm::stable_sort(
+      ctx.outputSections,
+      [this, &originalOrder](const OutputSection *a, const OutputSection *b) {
+        auto itA = ctx.config.sectionOrder.find(a->name.str());
+        auto itB = ctx.config.sectionOrder.find(b->name.str());
+
+        if (itA != ctx.config.sectionOrder.end() &&
+            itB != ctx.config.sectionOrder.end())
+          return itA->second < itB->second;
+
+        // Not found in layout file; respect the original order
+        return originalOrder[a] < originalOrder[b];
----------------
mstorsjo wrote:

I'm a little unsure about whether this sort function really does the right, intended thing (and what that really is). What's the intended behaviour of sections that aren't mentioned in the layout file?

Consider a layout file that says "sect3, sect1". After linking, we have "sect1, sect2, sect3". If we compare "sect1 < sect2", we don't find sect2 in the sectionOrder map, so we keep the original order. Same for "sect2 < sect3".

So in the current form, it seems like any unmentioned section pretty much blocks the sort from doing anything.

I'm not sure how this is supposed to work - intuitively, I would expect e.g. all the sections that are mentioned in the layout file to be sorted, in that order, before any other unspecified section.

I do see that there's a testcase exactly for this case though. Does `stable_sort` have any guarantees that it tests all combinations? Otherwise it seems to me that this sorting function is nondeterministic, depending on in which order the sorting implementation decides to compare things?

https://github.com/llvm/llvm-project/pull/152779


More information about the llvm-commits mailing list