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

via llvm-commits llvm-commits at lists.llvm.org
Sat Aug 30 00:02:23 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];
----------------
kkent030315 wrote:

It seems like MS link put the unspecified section after all specified sections.

```
1>mylayout.txt : warning LNK4290: section '.text' is missing specification in section layout file; will be put after all specified sections
```

> 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 this is expected to be: "sect3, sect1, sect2".

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


More information about the llvm-commits mailing list