← Back to Pull requests

[dyndbg][LLD][ELF] Support `--gc-sections` for dynamic debugging #233922

Open
nga888 opened this pull request with 504 lines diff across 10 files
View on GitHub
nga888 nga888 commented on Oct 20, 2026 17:36 UTC
Author

When --gc-sections is enabled for dynamic debugging, determine any additional unoptimized "inner" dependencies on the optimized "outer" during the mark live of the "outer" link. This is achieved by scanning the relocations of unoptimized "inner" __dyndbg. prefixed equivalents of the "outer" live symbols. These live unoptimized "inner" symbols then also become the GC roots for the mark live of the "inner" --gc-sections relocatable link.

In "dynamic-debug.test", separate the --gc-sections related "negative" checks so that they are more robust and avoid any issues with regards to the "positive" DAG checks.

Diff: 504 lines (+418 / -86) across 10 files Reviewer: smithp35 Review duration: 64221m
All Vouch review confidence checks passed
Residual risk 0.07 = Change Risk (0.60) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.60 · 504 lines diff across 10 files
0.60
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.372
Real PR Conversation Timeline
28 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 20, 2026 17:37 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-lld-elf

Author: Andrew Ng (nga888)

<details>
<summary>Changes</summary>

When --gc-sections is enabled for dynamic debugging, determine any additional unoptimized "inner" dependencies on the optimized "outer" during the mark live of the "outer" link. This is achieved by scanning the relocations of unoptimized "inner" __dyndbg. prefixed equivalents of the "outer" live symbols. These live unoptimized "inner" symbols then also become the GC roots for the mark live of the "inner" --gc-sections relocatable link.

In "dynamic-debug.test", separate the --gc-sections related "negative" checks so that they are more robust and avoid any issues with regards to the "positive" DAG checks.

---

Patch is 34.41 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/233922.diff

10 Files Affected:

  • (modified) lld/ELF/Config.h (+5)

  • (modified) lld/ELF/Driver.cpp (+8-3)

  • (modified) lld/ELF/InputFiles.cpp (+168-22)

  • (modified) lld/ELF/InputFiles.h (+25-2)

  • (modified) lld/ELF/InputSection.cpp (+25)

  • (modified) lld/ELF/InputSection.h (+12-1)

  • (modified) lld/ELF/MarkLive.cpp (+79-31)

  • (modified) lld/ELF/Writer.cpp (+4-3)

  • (modified) lld/test/ELF/dynamic-debug.test (+86-23)

  • (modified) llvm/docs/DynamicDebugging.md (-1)
  • ``````

    diff --git a/lld/ELF/Config.h b/lld/ELF/Config.h
    index 0c76e3854e660..fada969433dbf 100644
    --- a/lld/ELF/Config.h
    +++ b/lld/ELF/Config.h
    @@ -801,6 +801,11 @@ struct Ctx : CommonLinkerContext {
       // Pointer to the output of the embedded unoptimized dynamic debugging
       // relocatable link.
       std::unique_ptr<llvm::FileOutputBuffer> dynDbgOutput;
    +  // GC roots for the dynamic debugging relocatable link.
    +  SmallVector<llvm::StringRef, 0> dynDbgGCRoots;
    +  // Mutex pool used by ObjFile::maybeCreateDynDbgGCInfo(). Use a pool of
    +  // mutexes rather than one per object file.
    +  std::vector<std::mutex> dynDbgGCMutexPool;
     };
     
     // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
    diff --git a/lld/ELF/Driver.cpp b/lld/ELF/Driver.cpp
    index 966b12f46e687..44b16f769c53a 100644
    --- a/lld/ELF/Driver.cpp
    +++ b/lld/ELF/Driver.cpp
    @@ -3260,9 +3260,10 @@ static void linkDynamicDebug(Ctx &ctx, ArrayRef<WrappedSymbol> wrapped) {
     
       for (auto *file : ctx.objectFiles) {
         auto *obj = cast<ObjFile<ELFT>>(file);
    -    if (obj->dynDbgSec) {
    -      MemoryBufferRef mb(toStringRef(obj->dynDbgSec->contentMaybeDecompress()),
    -                         obj->mb.getBufferIdentifier());
    +    if (obj->dynDbgInfo) {
    +      MemoryBufferRef mb(
    +          toStringRef(obj->dynDbgInfo->inputSec->contentMaybeDecompress()),
    +          obj->mb.getBufferIdentifier());
           dctx.driver.addFile(createObjFile(dctx, mb));
         }
       }
    @@ -3276,6 +3277,10 @@ static void linkDynamicDebug(Ctx &ctx, ArrayRef<WrappedSymbol> wrapped) {
           saveArg(Twine("-O") + Twine(ctx.arg.optimize))};
       if (ctx.arg.resolveGroups)
         args.push_back("--force-group-allocation");
    +  if (ctx.arg.gcSections) {
    +    dctx.dynDbgGCRoots = std::move(ctx.dynDbgGCRoots);
    +    args.push_back("--gc-sections");
    +  }
       for (const auto &ws : wrapped)
         args.push_back(saveArg(Twine("--wrap=") + ws.sym->getName()));
       dctx.driver.linkerMain(args);
    diff --git a/lld/ELF/InputFiles.cpp b/lld/ELF/InputFiles.cpp
    index a1f921a875605..1295362b6c9cf 100644
    --- a/lld/ELF/InputFiles.cpp
    +++ b/lld/ELF/InputFiles.cpp
    @@ -646,7 +646,8 @@ template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
         if (sec.sh_type == SHT_LLVM_DYNDBG_ELF) {
           if (check(obj.getSectionName(sec, shstrtab)) == dynDbgSecName) {
             sections[i] = &InputSection::discarded;
    -        dynDbgSec = std::make_unique<InputSection>(*this, sec, dynDbgSecName);
    +        dynDbgInfo = std::make_unique<DynDbgInfo>(
    +            new InputSection(*this, sec, dynDbgSecName));
             ctx.hasDynDbg = true;
           }
           continue;
    @@ -1197,6 +1198,30 @@ InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
       return makeThreadLocal<InputSection>(*this, sec, name);
     }
     
    +template <typename ELFT>
    +void ObjFile<ELFT>::visitGlobalRelocSymbolIndices(
    +    const object::ELFFile<ELFT> &obj, const Elf_Shdr &sh,
    +    llvm::function_ref<void(uint32_t)> fn) const {
    +  auto visit = [&](uint32_t symIdx) {
    +    if (symIdx >= firstGlobal)
    +      fn(symIdx);
    +  };
    +
    +  if (sh.sh_type == SHT_CREL) {
    +    auto [rels, relas] = CHECK2(obj.crels(sh), this);
    +    for (const Elf_Rel &r : rels)
    +      visit(r.getSymbol(false));
    +    for (const Elf_Rela &r : relas)
    +      visit(r.getSymbol(false));
    +  } else if (sh.sh_type == SHT_RELA) {
    +    for (const Elf_Rela &r : CHECK2(obj.relas(sh), this))
    +      visit(r.getSymbol(ctx.arg.isMips64EL));
    +  } else {
    +    for (const Elf_Rel &r : CHECK2(obj.rels(sh), this))
    +      visit(r.getSymbol(ctx.arg.isMips64EL));
    +  }
    +}
    +
     // Initialize symbols. symbols is a parallel array to the corresponding ELF
     // symbol table.
     template <class ELFT>
    @@ -1259,7 +1284,7 @@ void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
         sym->referenced = true;
       }
     
    -  if (dynDbgSec)
    +  if (dynDbgInfo)
         initDynDbgSymbols();
     }
     
    @@ -1268,8 +1293,9 @@ void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
     // those reached by an inner relocation against a SHF_ALLOC section with
     // `isDynDbgRef`; the rest are only needed by debug sections.
     template <class ELFT> void ObjFile<ELFT>::initDynDbgSymbols() {
    -  MemoryBufferRef dbgMb(toStringRef(dynDbgSec->contentMaybeDecompress()),
    -                        mb.getBufferIdentifier());
    +  MemoryBufferRef dbgMb(
    +      toStringRef(dynDbgInfo->inputSec->contentMaybeDecompress()),
    +      mb.getBufferIdentifier());
       std::unique_ptr<ELFFileBase> efb = createObjFile(ctx, dbgMb);
       // Compare ekind (note ObjFile<ELFT>::classof only tests InputFile::kind()).
       if (efb->ekind != ekind) {
    @@ -1282,30 +1308,16 @@ template <class ELFT> void ObjFile<ELFT>::initDynDbgSymbols() {
     
       ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getGlobalELFSyms<ELFT>();
       SmallVector<bool, 0> globalUsed(dbgSyms.size());
    -  auto setSymUsed = [&, firstGlobal = dbgObj.firstGlobal](uint32_t symIdx) {
    -    if (symIdx >= firstGlobal)
    -      globalUsed[symIdx - firstGlobal] = true;
    -  };
    -
       for (const Elf_Shdr &sh : dbgObj.template getELFShdrs<ELFT>()) {
         if (!isStaticRelSecType(sh.sh_type))
           continue;
         const Elf_Shdr &target = *CHECK2(obj.getSection(sh.sh_info), &dbgObj);
         if (!(target.sh_flags & SHF_ALLOC))
           continue;
    -    if (sh.sh_type == SHT_CREL) {
    -      auto [rels, relas] = CHECK2(obj.crels(sh), &dbgObj);
    -      for (const Elf_Rel &r : rels)
    -        setSymUsed(r.getSymbol(false));
    -      for (const Elf_Rela &r : relas)
    -        setSymUsed(r.getSymbol(false));
    -    } else if (sh.sh_type == SHT_RELA) {
    -      for (const Elf_Rela &r : CHECK2(obj.relas(sh), &dbgObj))
    -        setSymUsed(r.getSymbol(ctx.arg.isMips64EL));
    -    } else {
    -      for (const Elf_Rel &r : CHECK2(obj.rels(sh), &dbgObj))
    -        setSymUsed(r.getSymbol(ctx.arg.isMips64EL));
    -    }
    +    dbgObj.visitGlobalRelocSymbolIndices(
    +        obj, sh, [&, firstGlobal = dbgObj.firstGlobal](uint32_t symIdx) {
    +          globalUsed[symIdx - firstGlobal] = true;
    +        });
       }
     
       for (size_t i = 0, end = dbgSyms.size(); i != end; ++i) {
    @@ -1323,6 +1335,10 @@ template <class ELFT> void ObjFile<ELFT>::initDynDbgSymbols() {
             Msg(ctx) << this << ": dynamic debugging reference to " << name;
         }
       }
    +
    +  // Keep hold of the ELF object file for `--gc-sections`.
    +  if (ctx.arg.gcSections)
    +    dynDbgInfo->elf = std::move(efb);
     }
     
     template <class ELFT>
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the
    +// GC roots for the "inner" `--gc-sections` mark live.
    +template <typename ELFT> void ObjFile<ELFT>::maybeCreateDynDbgGCInfo() {
    +  if (!dynDbgInfo || dynDbgInfo->gcInfoCreated || !dynDbgInfo->elf)
    +    return;
    +
    +  LockGuard lock(this, ctx.dynDbgGCMutexPool);
    +  if (dynDbgInfo->gcInfoCreated)
    +    return;
    +
    +  auto *symtab = ctx.symtab.get();
    +  auto &dbgObj = cast<ObjFile<ELFT>>(*(dynDbgInfo->elf));
    +  const object::ELFFile<ELFT> obj = dbgObj.getObj();
    +  ArrayRef<Elf_Shdr> dbgShdrs = dbgObj.template getELFShdrs<ELFT>();
    +  uint32_t numDbgShdrs = dbgShdrs.size();
    +
    +  // Used to record a section's relocation section index and whether the section
    +  // has already been processed.
    +  struct SecInfo {
    +    uint32_t relocIdx;
    +    bool processed;
    +  };
    +  SmallVector<SecInfo, 0> secInfos(numDbgShdrs);
    +
    +  // Populate relocation section indices and any extended symbol index table.
    +  for (uint32_t secIdx = 1; secIdx < numDbgShdrs; ++secIdx) {
    +    const Elf_Shdr &sh = dbgShdrs[secIdx];
    +    if (isStaticRelSecType(sh.sh_type))
    +      secInfos[sh.sh_info].relocIdx = secIdx;
    +    else if (sh.sh_type == SHT_SYMTAB_SHNDX)
    +      dbgObj.shndxTable = CHECK2(obj.getSHNDXTable(sh, dbgShdrs), &dbgObj);
    +  }
    +
    +  ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getELFSyms<ELFT>();
    +  for (uint32_t i = dbgObj.firstGlobal, end = dbgSyms.size(); i != end; ++i) {
    +    const Elf_Sym &s = dbgSyms[i];
    +    uint32_t secIdx = s.st_shndx;
    +    if (secIdx == SHN_UNDEF)
    +      continue;
    +
    +    if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
    +      secIdx =
    +          check(getExtendedSymbolTableIndex<ELFT>(s, i, dbgObj.shndxTable));
    +    else if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE))
    +      continue;
    +
    +    SecInfo &si = secInfos[secIdx];
    +    if (si.processed)
    +      continue;
    +
    +    // Only interested in dynamic debugging "inner" `__dyndbg.` prefixed
    +    // symbols.
    +    StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +    if (!name.starts_with("__dyndbg."))
    +      continue;
    +
    +    si.processed = true;
    +
    +    // Try to find the matching "outer" symbol.
    +    Symbol *sym = symtab->find(name.drop_front(9));
    +    if (!sym || !sym->isDefined() || sym->file != this)
    +      continue;
    +
    +    InputSection *is = dyn_cast<InputSection>(cast<Defined>(sym)->section);
    +    if (!is)
    +      continue;
    +
    +    assert(is->file == this);
    +
    +    // Get or create the InputSection's DynDbgGCInfo.
    +    DynDbgGCInfo *gcInfo = is->dynDbgGCInfo;
    +    if (!gcInfo) {
    +      gcInfo = new DynDbgGCInfo;
    +      dynDbgInfo->gcInfos.emplace_back(std::unique_ptr<DynDbgGCInfo>(gcInfo));
    +      is->dynDbgGCInfo = gcInfo;
    +    }
    +
    +    // Add this "inner" `__dyndbg.` prefixed symbol as a GC root.
    +    gcInfo->roots.push_back(name);
    +
    +    if (!si.relocIdx)
    +      continue;
    +
    +    // Find "outer" symbols referenced by the "inner" and record in the
    +    // InputSection's DynDbgGCInfo.
    +    DenseSet<uint32_t> processedSyms;
    +    dbgObj.visitGlobalRelocSymbolIndices(
    +        obj, dbgShdrs[si.relocIdx], [&](uint32_t symIdx) {
    +          const Elf_Sym &s = dbgSyms[symIdx];
    +          if (s.st_shndx != SHN_UNDEF || !processedSyms.insert(symIdx).second)
    +            return;
    +
    +          StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +          Symbol *sym = symtab->find(name);
    +          if (sym && (sym->isDefined() || sym->isShared()))
    +            gcInfo->refs.push_back(sym);
    +        });
    +  }
    +
    +  dynDbgInfo->gcInfoCreated = true;
    +  dynDbgInfo->elf.reset(); // ELF file no longer required.
    +}
    +
     template class elf::ObjFile<ELF32LE>;
     template class elf::ObjFile<ELF32BE>;
     template class elf::ObjFile<ELF64LE>;
    diff --git a/lld/ELF/InputFiles.h b/lld/ELF/InputFiles.h
    index 5c4e060e2331b..a974383db36d5 100644
    --- a/lld/ELF/InputFiles.h
    +++ b/lld/ELF/InputFiles.h
    @@ -236,6 +236,23 @@ class ELFFileBase : public InputFile {
       std::optional<AArch64PauthAbiCoreInfo> aarch64PauthAbiCoreInfo;
     };
     
    +// Dynamic debugging info.
    +struct DynDbgGCInfo;
    +
    +struct DynDbgInfo {
    +  // Embedded unoptimized dynamic debug input section.
    +  std::unique_ptr<InputSection> inputSec;
    +
    +  // The following are used for `--gc-sections` support.
    +  std::atomic<bool> gcInfoCreated = false;
    +  std::unique_ptr<ELFFileBase> elf;
    +  // Lifetime control of DynDbgGCInfo in InputSection is not straightforward, so
    +  // do so from here instead.
    +  SmallVector<std::unique_ptr<DynDbgGCInfo>, 0> gcInfos;
    +
    +  DynDbgInfo(InputSection *is);
    +};
    +
     // .o file.
     template <class ELFT> class ObjFile : public ELFFileBase {
       LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
    @@ -264,8 +281,14 @@ template <class ELFT> class ObjFile : public ELFFileBase {
       // Pointer to this input file's .llvm_addrsig section, if it has one.
       const Elf_Shdr *addrsigSec = nullptr;
     
    -  // Embedded unoptimized dynamic debug input section.
    -  std::unique_ptr<InputSection> dynDbgSec;
    +  // Dynamic debugging info.
    +  std::unique_ptr<DynDbgInfo> dynDbgInfo;
    +
    +  void
    +  visitGlobalRelocSymbolIndices(const llvm::object::ELFFile<ELFT> &obj,
    +                                const Elf_Shdr &relocShdr,
    +                                llvm::function_ref<void(uint32_t)> func) const;
    +  void maybeCreateDynDbgGCInfo();
     
       // SHT_LLVM_CALL_GRAPH_PROFILE section index.
       uint32_t cgProfileSectionIndex = 0;
    diff --git a/lld/ELF/InputSection.cpp b/lld/ELF/InputSection.cpp
    index 13baaa5b8c2ad..26ab4ec9c00cf 100644
    --- a/lld/ELF/InputSection.cpp
    +++ b/lld/ELF/InputSection.cpp
    @@ -1359,6 +1359,31 @@ void InputSection::replace(InputSection *other) {
       other->markDead();
     }
     
    +const DynDbgGCInfo *InputSection::getDynDbgGCInfo() const {
    +  if (file->kind() != InputFile::ObjKind)
    +    return nullptr;
    +
    +  ELFFileBase *efb = cast<ELFFileBase>(file);
    +  switch (efb->ekind) {
    +  case ELF32LEKind:
    +    cast<ObjFile<ELF32LE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  case ELF32BEKind:
    +    cast<ObjFile<ELF32BE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  case ELF64LEKind:
    +    cast<ObjFile<ELF64LE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  case ELF64BEKind:
    +    cast<ObjFile<ELF64BE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  default:
    +    llvm_unreachable("");
    +  }
    +
    +  return dynDbgGCInfo;
    +}
    +
     template <class ELFT>
     EhInputSection::EhInputSection(ObjFile<ELFT> &f,
                                    const typename ELFT::Shdr &header,
    diff --git a/lld/ELF/InputSection.h b/lld/ELF/InputSection.h
    index bbc5dda2efbd1..5ce4d33212ba2 100644
    --- a/lld/ELF/InputSection.h
    +++ b/lld/ELF/InputSection.h
    @@ -32,6 +32,14 @@ class SyntheticSection;
     template <class ELFT> class ObjFile;
     class OutputSection;
     
    +// Per InputSection dynamic debugging info to support `--gc-sections`.
    +struct DynDbgGCInfo {
    +  // The "inner" GC roots for this InputSection.
    +  SmallVector<StringRef, 1> roots;
    +  // The "outer" symbols referenced by "inner" symbols for this InputSection.
    +  SmallVector<Symbol *, 0> refs;
    +};
    +
     // Returned by InputSectionBase::relsOrRelas. At least two members are empty.
     template <class ELFT> struct RelsOrRelas {
       Relocs<typename ELFT::Rel> rels;
    @@ -461,6 +469,9 @@ class InputSection : public InputSectionBase {
       // Called by ICF to merge two input sections.
       void replace(InputSection *other);
     
    +  DynDbgGCInfo *dynDbgGCInfo = nullptr;
    +  const DynDbgGCInfo *getDynDbgGCInfo() const;
    +
       static InputSection discarded;
     
     private:
    @@ -493,7 +504,7 @@ class PotentialSpillSection : public InputSection {
     };
     
     #ifndef _WIN32
    -static_assert(sizeof(InputSection) <= 152, "InputSection is too big");
    +static_assert(sizeof(InputSection) <= 160, "InputSection is too big");
     #endif
     
     class SyntheticSection : public InputSection {
    diff --git a/lld/ELF/MarkLive.cpp b/lld/ELF/MarkLive.cpp
    index f5179bb2c60d0..c1393bc5ac028 100644
    --- a/lld/ELF/MarkLive.cpp
    +++ b/lld/ELF/MarkLive.cpp
    @@ -370,20 +370,11 @@ template <class ELFT, bool TrackWhyLive>
     void MarkLive<ELFT, TrackWhyLive>::run() {
       // Add GC root symbols.
     
    -  for (Symbol *sym : ctx.symtab->getSymbols()) {
    -    // For now, preserve all symbols required by the embedded unoptimized part
    -    // of dynamic debugging. TODO: better support for `--gc-sections`.
    -    if (sym->isDynDbgRef) {
    -      markSymbol(sym, "dynamic debugging");
    -      sym->setFlags(USED);
    -      continue;
    -    }
    -
    -    // Preserve externally-visible symbols if the symbols defined by this
    -    // file can interpose other ELF file's symbols at runtime.
    +  // Preserve externally-visible symbols if the symbols defined by this
    +  // file can interpose other ELF file's symbols at runtime.
    +  for (Symbol *sym : ctx.symtab->getSymbols())
         if (sym->isExported)
           markSymbol(sym, "externally visible symbol");
    -  }
     
       markSymbol(ctx.symtab->find(ctx.arg.entry), "entry point");
       markSymbol(ctx.symtab->find(ctx.arg.init), "initializer function");
    @@ -397,6 +388,10 @@ void MarkLive<ELFT, TrackWhyLive>::run() {
         markSymbol(ctx.symtab->cmseSymMap[symName].acleSeSym, "ARM CMSE symbol");
       }
     
    +  if (ctx.inDynDbgLink)
    +    for (const StringRef &s : ctx.dynDbgGCRoots)
    +      markSymbol(ctx.symtab->find(s), "dynamic debugging");
    +
       // Mark .eh_frame sections as live because there are usually no relocations
       // that point to .eh_frames. Otherwise, the garbage collector would drop
       // all of them. We also want to preserve personality routines and LSDA
    @@ -405,7 +400,7 @@ void MarkLive<ELFT, TrackWhyLive>::run() {
         scanEhFrameSection(*eh);
       // See markUsedSymbols.
       bool markUsed =
    -      ctx.arg.copyRelocs &&
    +      ctx.arg.copyRelocs && !ctx.dynDbgRelocatable &&
           (ctx.arg.discard != DiscardPolicy::None || ctx.arg.retainSymbols);
       for (InputSectionBase *sec : ctx.inputSections) {
         if (sec->flags & SHF_GNU_RETAIN) {
    @@ -489,6 +484,9 @@ void MarkLive<ELFT, TrackWhyLive>::run() {
     
     template <class ELFT, bool TrackWhyLive>
     void MarkLive<ELFT, TrackWhyLive>::mark() {
    +  if (ctx.hasDynDbg && ctx.dynDbgGCMutexPool.empty())
    +    ctx.dynDbgGCMutexPool = std::vector<std::mutex>(ctx.arg.threadCount);
    +
       if constexpr (!TrackWhyLive) {
         markParallel();
         return;
    @@ -504,6 +502,25 @@ void MarkLive<ELFT, TrackWhyLive>::mark() {
         for (const typename ELFT::Crel &rel : rels.crels)
           resolveReloc(sec, rel, false);
     
    +    if (ctx.hasDynDbg) {
    +      if (InputSection *is = dyn_cast<InputSection>(&sec)) {
    +        if (const DynDbgGCInfo *gi = is->getDynDbgGCInfo()) {
    +          ctx.dynDbgGCRoots.append(gi->roots);
    +
    +          for (Symbol *sym : gi->refs) {
    +            sym->setFlags(USED);
    +            if (auto *ss = dyn_cast<SharedSymbol>(sym)) {
    +              if (!ss->isWeak())
    +                whyLive.try_emplace(sym, LiveReason{is, "dynamic debugging"});
    +            } else if (auto *d = dyn_cast<Defined>(sym)) {
    +              if (auto *isec = dyn_cast_or_null<InputSectionBase>(d->section))
    +                enqueue(isec, d->value, sym, {is, "dynamic debugging"});
    +            }
    +          }
    +        }
    +      }
    +    }
    +
         for (InputSectionBase *isec : sec.dependentSections)
           enqueue(isec, /*offset=*/0, /*sym=*/nullptr,
                   {&sec, "depended on by section"});
    @@ -524,7 +541,17 @@ static void processSectionEdges(
         Ctx &ctx, InputSectionBase &sec,
         const DenseMap<StringRef, SmallVector<InputSectionBase *, 0>>
             &cNamedSections,
    -    Fn fn) {
    +    SmallVector<StringRef, 0> &ddGCRoots, Fn fn) {
    +  auto markIfSectionPiece = [&](auto *isec, uint64_t offset) {
    +    if (auto *ms = dyn_cast<MergeInputSection>(isec)) {
    +      auto &piece = ms->getSectionPiece(offset);
    +      auto *word =
    +          reinterpret_cast<std::atomic<uint32_t> *>(&piece.inputOff + 1);
    +      constexpr uint32_t liveBit = sys::IsBigEndianHost ? (1U << 31) : 1U;
    +      word->fetch_or(liveBit, std::memory_order_relaxed);
    +    }
    +  };
    +
       auto resolveEdge = [&](const auto &rel) {
         Symbol &sym = sec.file->getRelocTargetSym(rel);
         if (!sym.hasFlag(USED))
    @@ -538,13 +565,7 @@ static void processSectionEdges(
                   ms && offset >= ms->content().size())
                 return;
             }
    -        if (auto *ms = dyn_cast<MergeInputSection>(relSec)) {
    -          auto &piece = ms->getSectionPiece(offset);
    -          auto *word =
    -              reinterpret_cast<std::atomic<uint32_t> *>(&piece.inputOff + 1);
    -          constexpr uint32_t liveBit = sys::IsBigEndianHost ? (1U << 31) : 1U;
    -          word->fetch_or(liveBit, std::memory_order_relaxed);
    -        }
    +        markIfSectionPiece(relSec, offset);
             fn(relSec, offset);
           }
           return;
    @@ -563,6 +584,26 @@ static void processSectionEdges(
         fn(isec, 0);
       if (sec.nextInSectionGroup)
         fn(sec.nextInSectionGroup, 0);
    +
    +  if (ctx.hasDynDbg) {
    +    if (InputSection *is = dyn_cast<InputSection>(&sec)) {
    +    ...
    [truncated]
    
    
    ``````

    </details>

    llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 20, 2026 17:37 UTC
    Bot

    <!--LLVM PR SUMMARY COMMENT-->

    @llvm/pr-subscribers-lld

    Author: Andrew Ng (nga888)

    <details>
    <summary>Changes</summary>

    When --gc-sections is enabled for dynamic debugging, determine any additional unoptimized "inner" dependencies on the optimized "outer" during the mark live of the "outer" link. This is achieved by scanning the relocations of unoptimized "inner" __dyndbg. prefixed equivalents of the "outer" live symbols. These live unoptimized "inner" symbols then also become the GC roots for the mark live of the "inner" --gc-sections relocatable link.

    In "dynamic-debug.test", separate the --gc-sections related "negative" checks so that they are more robust and avoid any issues with regards to the "positive" DAG checks.

    ---

    Patch is 34.41 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/233922.diff

    10 Files Affected:

  • (modified) lld/ELF/Config.h (+5)

  • (modified) lld/ELF/Driver.cpp (+8-3)

  • (modified) lld/ELF/InputFiles.cpp (+168-22)

  • (modified) lld/ELF/InputFiles.h (+25-2)

  • (modified) lld/ELF/InputSection.cpp (+25)

  • (modified) lld/ELF/InputSection.h (+12-1)

  • (modified) lld/ELF/MarkLive.cpp (+79-31)

  • (modified) lld/ELF/Writer.cpp (+4-3)

  • (modified) lld/test/ELF/dynamic-debug.test (+86-23)

  • (modified) llvm/docs/DynamicDebugging.md (-1)
  • ``````

    diff --git a/lld/ELF/Config.h b/lld/ELF/Config.h
    index 0c76e3854e660..fada969433dbf 100644
    --- a/lld/ELF/Config.h
    +++ b/lld/ELF/Config.h
    @@ -801,6 +801,11 @@ struct Ctx : CommonLinkerContext {
       // Pointer to the output of the embedded unoptimized dynamic debugging
       // relocatable link.
       std::unique_ptr<llvm::FileOutputBuffer> dynDbgOutput;
    +  // GC roots for the dynamic debugging relocatable link.
    +  SmallVector<llvm::StringRef, 0> dynDbgGCRoots;
    +  // Mutex pool used by ObjFile::maybeCreateDynDbgGCInfo(). Use a pool of
    +  // mutexes rather than one per object file.
    +  std::vector<std::mutex> dynDbgGCMutexPool;
     };
     
     // The first two elements of versionDefinitions represent VER_NDX_LOCAL and
    diff --git a/lld/ELF/Driver.cpp b/lld/ELF/Driver.cpp
    index 966b12f46e687..44b16f769c53a 100644
    --- a/lld/ELF/Driver.cpp
    +++ b/lld/ELF/Driver.cpp
    @@ -3260,9 +3260,10 @@ static void linkDynamicDebug(Ctx &ctx, ArrayRef<WrappedSymbol> wrapped) {
     
       for (auto *file : ctx.objectFiles) {
         auto *obj = cast<ObjFile<ELFT>>(file);
    -    if (obj->dynDbgSec) {
    -      MemoryBufferRef mb(toStringRef(obj->dynDbgSec->contentMaybeDecompress()),
    -                         obj->mb.getBufferIdentifier());
    +    if (obj->dynDbgInfo) {
    +      MemoryBufferRef mb(
    +          toStringRef(obj->dynDbgInfo->inputSec->contentMaybeDecompress()),
    +          obj->mb.getBufferIdentifier());
           dctx.driver.addFile(createObjFile(dctx, mb));
         }
       }
    @@ -3276,6 +3277,10 @@ static void linkDynamicDebug(Ctx &ctx, ArrayRef<WrappedSymbol> wrapped) {
           saveArg(Twine("-O") + Twine(ctx.arg.optimize))};
       if (ctx.arg.resolveGroups)
         args.push_back("--force-group-allocation");
    +  if (ctx.arg.gcSections) {
    +    dctx.dynDbgGCRoots = std::move(ctx.dynDbgGCRoots);
    +    args.push_back("--gc-sections");
    +  }
       for (const auto &ws : wrapped)
         args.push_back(saveArg(Twine("--wrap=") + ws.sym->getName()));
       dctx.driver.linkerMain(args);
    diff --git a/lld/ELF/InputFiles.cpp b/lld/ELF/InputFiles.cpp
    index a1f921a875605..1295362b6c9cf 100644
    --- a/lld/ELF/InputFiles.cpp
    +++ b/lld/ELF/InputFiles.cpp
    @@ -646,7 +646,8 @@ template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
         if (sec.sh_type == SHT_LLVM_DYNDBG_ELF) {
           if (check(obj.getSectionName(sec, shstrtab)) == dynDbgSecName) {
             sections[i] = &InputSection::discarded;
    -        dynDbgSec = std::make_unique<InputSection>(*this, sec, dynDbgSecName);
    +        dynDbgInfo = std::make_unique<DynDbgInfo>(
    +            new InputSection(*this, sec, dynDbgSecName));
             ctx.hasDynDbg = true;
           }
           continue;
    @@ -1197,6 +1198,30 @@ InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
       return makeThreadLocal<InputSection>(*this, sec, name);
     }
     
    +template <typename ELFT>
    +void ObjFile<ELFT>::visitGlobalRelocSymbolIndices(
    +    const object::ELFFile<ELFT> &obj, const Elf_Shdr &sh,
    +    llvm::function_ref<void(uint32_t)> fn) const {
    +  auto visit = [&](uint32_t symIdx) {
    +    if (symIdx >= firstGlobal)
    +      fn(symIdx);
    +  };
    +
    +  if (sh.sh_type == SHT_CREL) {
    +    auto [rels, relas] = CHECK2(obj.crels(sh), this);
    +    for (const Elf_Rel &r : rels)
    +      visit(r.getSymbol(false));
    +    for (const Elf_Rela &r : relas)
    +      visit(r.getSymbol(false));
    +  } else if (sh.sh_type == SHT_RELA) {
    +    for (const Elf_Rela &r : CHECK2(obj.relas(sh), this))
    +      visit(r.getSymbol(ctx.arg.isMips64EL));
    +  } else {
    +    for (const Elf_Rel &r : CHECK2(obj.rels(sh), this))
    +      visit(r.getSymbol(ctx.arg.isMips64EL));
    +  }
    +}
    +
     // Initialize symbols. symbols is a parallel array to the corresponding ELF
     // symbol table.
     template <class ELFT>
    @@ -1259,7 +1284,7 @@ void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
         sym->referenced = true;
       }
     
    -  if (dynDbgSec)
    +  if (dynDbgInfo)
         initDynDbgSymbols();
     }
     
    @@ -1268,8 +1293,9 @@ void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
     // those reached by an inner relocation against a SHF_ALLOC section with
     // `isDynDbgRef`; the rest are only needed by debug sections.
     template <class ELFT> void ObjFile<ELFT>::initDynDbgSymbols() {
    -  MemoryBufferRef dbgMb(toStringRef(dynDbgSec->contentMaybeDecompress()),
    -                        mb.getBufferIdentifier());
    +  MemoryBufferRef dbgMb(
    +      toStringRef(dynDbgInfo->inputSec->contentMaybeDecompress()),
    +      mb.getBufferIdentifier());
       std::unique_ptr<ELFFileBase> efb = createObjFile(ctx, dbgMb);
       // Compare ekind (note ObjFile<ELFT>::classof only tests InputFile::kind()).
       if (efb->ekind != ekind) {
    @@ -1282,30 +1308,16 @@ template <class ELFT> void ObjFile<ELFT>::initDynDbgSymbols() {
     
       ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getGlobalELFSyms<ELFT>();
       SmallVector<bool, 0> globalUsed(dbgSyms.size());
    -  auto setSymUsed = [&, firstGlobal = dbgObj.firstGlobal](uint32_t symIdx) {
    -    if (symIdx >= firstGlobal)
    -      globalUsed[symIdx - firstGlobal] = true;
    -  };
    -
       for (const Elf_Shdr &sh : dbgObj.template getELFShdrs<ELFT>()) {
         if (!isStaticRelSecType(sh.sh_type))
           continue;
         const Elf_Shdr &target = *CHECK2(obj.getSection(sh.sh_info), &dbgObj);
         if (!(target.sh_flags & SHF_ALLOC))
           continue;
    -    if (sh.sh_type == SHT_CREL) {
    -      auto [rels, relas] = CHECK2(obj.crels(sh), &dbgObj);
    -      for (const Elf_Rel &r : rels)
    -        setSymUsed(r.getSymbol(false));
    -      for (const Elf_Rela &r : relas)
    -        setSymUsed(r.getSymbol(false));
    -    } else if (sh.sh_type == SHT_RELA) {
    -      for (const Elf_Rela &r : CHECK2(obj.relas(sh), &dbgObj))
    -        setSymUsed(r.getSymbol(ctx.arg.isMips64EL));
    -    } else {
    -      for (const Elf_Rel &r : CHECK2(obj.rels(sh), &dbgObj))
    -        setSymUsed(r.getSymbol(ctx.arg.isMips64EL));
    -    }
    +    dbgObj.visitGlobalRelocSymbolIndices(
    +        obj, sh, [&, firstGlobal = dbgObj.firstGlobal](uint32_t symIdx) {
    +          globalUsed[symIdx - firstGlobal] = true;
    +        });
       }
     
       for (size_t i = 0, end = dbgSyms.size(); i != end; ++i) {
    @@ -1323,6 +1335,10 @@ template <class ELFT> void ObjFile<ELFT>::initDynDbgSymbols() {
             Msg(ctx) << this << ": dynamic debugging reference to " << name;
         }
       }
    +
    +  // Keep hold of the ELF object file for `--gc-sections`.
    +  if (ctx.arg.gcSections)
    +    dynDbgInfo->elf = std::move(efb);
     }
     
     template <class ELFT>
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the
    +// GC roots for the "inner" `--gc-sections` mark live.
    +template <typename ELFT> void ObjFile<ELFT>::maybeCreateDynDbgGCInfo() {
    +  if (!dynDbgInfo || dynDbgInfo->gcInfoCreated || !dynDbgInfo->elf)
    +    return;
    +
    +  LockGuard lock(this, ctx.dynDbgGCMutexPool);
    +  if (dynDbgInfo->gcInfoCreated)
    +    return;
    +
    +  auto *symtab = ctx.symtab.get();
    +  auto &dbgObj = cast<ObjFile<ELFT>>(*(dynDbgInfo->elf));
    +  const object::ELFFile<ELFT> obj = dbgObj.getObj();
    +  ArrayRef<Elf_Shdr> dbgShdrs = dbgObj.template getELFShdrs<ELFT>();
    +  uint32_t numDbgShdrs = dbgShdrs.size();
    +
    +  // Used to record a section's relocation section index and whether the section
    +  // has already been processed.
    +  struct SecInfo {
    +    uint32_t relocIdx;
    +    bool processed;
    +  };
    +  SmallVector<SecInfo, 0> secInfos(numDbgShdrs);
    +
    +  // Populate relocation section indices and any extended symbol index table.
    +  for (uint32_t secIdx = 1; secIdx < numDbgShdrs; ++secIdx) {
    +    const Elf_Shdr &sh = dbgShdrs[secIdx];
    +    if (isStaticRelSecType(sh.sh_type))
    +      secInfos[sh.sh_info].relocIdx = secIdx;
    +    else if (sh.sh_type == SHT_SYMTAB_SHNDX)
    +      dbgObj.shndxTable = CHECK2(obj.getSHNDXTable(sh, dbgShdrs), &dbgObj);
    +  }
    +
    +  ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getELFSyms<ELFT>();
    +  for (uint32_t i = dbgObj.firstGlobal, end = dbgSyms.size(); i != end; ++i) {
    +    const Elf_Sym &s = dbgSyms[i];
    +    uint32_t secIdx = s.st_shndx;
    +    if (secIdx == SHN_UNDEF)
    +      continue;
    +
    +    if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
    +      secIdx =
    +          check(getExtendedSymbolTableIndex<ELFT>(s, i, dbgObj.shndxTable));
    +    else if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE))
    +      continue;
    +
    +    SecInfo &si = secInfos[secIdx];
    +    if (si.processed)
    +      continue;
    +
    +    // Only interested in dynamic debugging "inner" `__dyndbg.` prefixed
    +    // symbols.
    +    StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +    if (!name.starts_with("__dyndbg."))
    +      continue;
    +
    +    si.processed = true;
    +
    +    // Try to find the matching "outer" symbol.
    +    Symbol *sym = symtab->find(name.drop_front(9));
    +    if (!sym || !sym->isDefined() || sym->file != this)
    +      continue;
    +
    +    InputSection *is = dyn_cast<InputSection>(cast<Defined>(sym)->section);
    +    if (!is)
    +      continue;
    +
    +    assert(is->file == this);
    +
    +    // Get or create the InputSection's DynDbgGCInfo.
    +    DynDbgGCInfo *gcInfo = is->dynDbgGCInfo;
    +    if (!gcInfo) {
    +      gcInfo = new DynDbgGCInfo;
    +      dynDbgInfo->gcInfos.emplace_back(std::unique_ptr<DynDbgGCInfo>(gcInfo));
    +      is->dynDbgGCInfo = gcInfo;
    +    }
    +
    +    // Add this "inner" `__dyndbg.` prefixed symbol as a GC root.
    +    gcInfo->roots.push_back(name);
    +
    +    if (!si.relocIdx)
    +      continue;
    +
    +    // Find "outer" symbols referenced by the "inner" and record in the
    +    // InputSection's DynDbgGCInfo.
    +    DenseSet<uint32_t> processedSyms;
    +    dbgObj.visitGlobalRelocSymbolIndices(
    +        obj, dbgShdrs[si.relocIdx], [&](uint32_t symIdx) {
    +          const Elf_Sym &s = dbgSyms[symIdx];
    +          if (s.st_shndx != SHN_UNDEF || !processedSyms.insert(symIdx).second)
    +            return;
    +
    +          StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +          Symbol *sym = symtab->find(name);
    +          if (sym && (sym->isDefined() || sym->isShared()))
    +            gcInfo->refs.push_back(sym);
    +        });
    +  }
    +
    +  dynDbgInfo->gcInfoCreated = true;
    +  dynDbgInfo->elf.reset(); // ELF file no longer required.
    +}
    +
     template class elf::ObjFile<ELF32LE>;
     template class elf::ObjFile<ELF32BE>;
     template class elf::ObjFile<ELF64LE>;
    diff --git a/lld/ELF/InputFiles.h b/lld/ELF/InputFiles.h
    index 5c4e060e2331b..a974383db36d5 100644
    --- a/lld/ELF/InputFiles.h
    +++ b/lld/ELF/InputFiles.h
    @@ -236,6 +236,23 @@ class ELFFileBase : public InputFile {
       std::optional<AArch64PauthAbiCoreInfo> aarch64PauthAbiCoreInfo;
     };
     
    +// Dynamic debugging info.
    +struct DynDbgGCInfo;
    +
    +struct DynDbgInfo {
    +  // Embedded unoptimized dynamic debug input section.
    +  std::unique_ptr<InputSection> inputSec;
    +
    +  // The following are used for `--gc-sections` support.
    +  std::atomic<bool> gcInfoCreated = false;
    +  std::unique_ptr<ELFFileBase> elf;
    +  // Lifetime control of DynDbgGCInfo in InputSection is not straightforward, so
    +  // do so from here instead.
    +  SmallVector<std::unique_ptr<DynDbgGCInfo>, 0> gcInfos;
    +
    +  DynDbgInfo(InputSection *is);
    +};
    +
     // .o file.
     template <class ELFT> class ObjFile : public ELFFileBase {
       LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
    @@ -264,8 +281,14 @@ template <class ELFT> class ObjFile : public ELFFileBase {
       // Pointer to this input file's .llvm_addrsig section, if it has one.
       const Elf_Shdr *addrsigSec = nullptr;
     
    -  // Embedded unoptimized dynamic debug input section.
    -  std::unique_ptr<InputSection> dynDbgSec;
    +  // Dynamic debugging info.
    +  std::unique_ptr<DynDbgInfo> dynDbgInfo;
    +
    +  void
    +  visitGlobalRelocSymbolIndices(const llvm::object::ELFFile<ELFT> &obj,
    +                                const Elf_Shdr &relocShdr,
    +                                llvm::function_ref<void(uint32_t)> func) const;
    +  void maybeCreateDynDbgGCInfo();
     
       // SHT_LLVM_CALL_GRAPH_PROFILE section index.
       uint32_t cgProfileSectionIndex = 0;
    diff --git a/lld/ELF/InputSection.cpp b/lld/ELF/InputSection.cpp
    index 13baaa5b8c2ad..26ab4ec9c00cf 100644
    --- a/lld/ELF/InputSection.cpp
    +++ b/lld/ELF/InputSection.cpp
    @@ -1359,6 +1359,31 @@ void InputSection::replace(InputSection *other) {
       other->markDead();
     }
     
    +const DynDbgGCInfo *InputSection::getDynDbgGCInfo() const {
    +  if (file->kind() != InputFile::ObjKind)
    +    return nullptr;
    +
    +  ELFFileBase *efb = cast<ELFFileBase>(file);
    +  switch (efb->ekind) {
    +  case ELF32LEKind:
    +    cast<ObjFile<ELF32LE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  case ELF32BEKind:
    +    cast<ObjFile<ELF32BE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  case ELF64LEKind:
    +    cast<ObjFile<ELF64LE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  case ELF64BEKind:
    +    cast<ObjFile<ELF64BE>>(efb)->maybeCreateDynDbgGCInfo();
    +    break;
    +  default:
    +    llvm_unreachable("");
    +  }
    +
    +  return dynDbgGCInfo;
    +}
    +
     template <class ELFT>
     EhInputSection::EhInputSection(ObjFile<ELFT> &f,
                                    const typename ELFT::Shdr &header,
    diff --git a/lld/ELF/InputSection.h b/lld/ELF/InputSection.h
    index bbc5dda2efbd1..5ce4d33212ba2 100644
    --- a/lld/ELF/InputSection.h
    +++ b/lld/ELF/InputSection.h
    @@ -32,6 +32,14 @@ class SyntheticSection;
     template <class ELFT> class ObjFile;
     class OutputSection;
     
    +// Per InputSection dynamic debugging info to support `--gc-sections`.
    +struct DynDbgGCInfo {
    +  // The "inner" GC roots for this InputSection.
    +  SmallVector<StringRef, 1> roots;
    +  // The "outer" symbols referenced by "inner" symbols for this InputSection.
    +  SmallVector<Symbol *, 0> refs;
    +};
    +
     // Returned by InputSectionBase::relsOrRelas. At least two members are empty.
     template <class ELFT> struct RelsOrRelas {
       Relocs<typename ELFT::Rel> rels;
    @@ -461,6 +469,9 @@ class InputSection : public InputSectionBase {
       // Called by ICF to merge two input sections.
       void replace(InputSection *other);
     
    +  DynDbgGCInfo *dynDbgGCInfo = nullptr;
    +  const DynDbgGCInfo *getDynDbgGCInfo() const;
    +
       static InputSection discarded;
     
     private:
    @@ -493,7 +504,7 @@ class PotentialSpillSection : public InputSection {
     };
     
     #ifndef _WIN32
    -static_assert(sizeof(InputSection) <= 152, "InputSection is too big");
    +static_assert(sizeof(InputSection) <= 160, "InputSection is too big");
     #endif
     
     class SyntheticSection : public InputSection {
    diff --git a/lld/ELF/MarkLive.cpp b/lld/ELF/MarkLive.cpp
    index f5179bb2c60d0..c1393bc5ac028 100644
    --- a/lld/ELF/MarkLive.cpp
    +++ b/lld/ELF/MarkLive.cpp
    @@ -370,20 +370,11 @@ template <class ELFT, bool TrackWhyLive>
     void MarkLive<ELFT, TrackWhyLive>::run() {
       // Add GC root symbols.
     
    -  for (Symbol *sym : ctx.symtab->getSymbols()) {
    -    // For now, preserve all symbols required by the embedded unoptimized part
    -    // of dynamic debugging. TODO: better support for `--gc-sections`.
    -    if (sym->isDynDbgRef) {
    -      markSymbol(sym, "dynamic debugging");
    -      sym->setFlags(USED);
    -      continue;
    -    }
    -
    -    // Preserve externally-visible symbols if the symbols defined by this
    -    // file can interpose other ELF file's symbols at runtime.
    +  // Preserve externally-visible symbols if the symbols defined by this
    +  // file can interpose other ELF file's symbols at runtime.
    +  for (Symbol *sym : ctx.symtab->getSymbols())
         if (sym->isExported)
           markSymbol(sym, "externally visible symbol");
    -  }
     
       markSymbol(ctx.symtab->find(ctx.arg.entry), "entry point");
       markSymbol(ctx.symtab->find(ctx.arg.init), "initializer function");
    @@ -397,6 +388,10 @@ void MarkLive<ELFT, TrackWhyLive>::run() {
         markSymbol(ctx.symtab->cmseSymMap[symName].acleSeSym, "ARM CMSE symbol");
       }
     
    +  if (ctx.inDynDbgLink)
    +    for (const StringRef &s : ctx.dynDbgGCRoots)
    +      markSymbol(ctx.symtab->find(s), "dynamic debugging");
    +
       // Mark .eh_frame sections as live because there are usually no relocations
       // that point to .eh_frames. Otherwise, the garbage collector would drop
       // all of them. We also want to preserve personality routines and LSDA
    @@ -405,7 +400,7 @@ void MarkLive<ELFT, TrackWhyLive>::run() {
         scanEhFrameSection(*eh);
       // See markUsedSymbols.
       bool markUsed =
    -      ctx.arg.copyRelocs &&
    +      ctx.arg.copyRelocs && !ctx.dynDbgRelocatable &&
           (ctx.arg.discard != DiscardPolicy::None || ctx.arg.retainSymbols);
       for (InputSectionBase *sec : ctx.inputSections) {
         if (sec->flags & SHF_GNU_RETAIN) {
    @@ -489,6 +484,9 @@ void MarkLive<ELFT, TrackWhyLive>::run() {
     
     template <class ELFT, bool TrackWhyLive>
     void MarkLive<ELFT, TrackWhyLive>::mark() {
    +  if (ctx.hasDynDbg && ctx.dynDbgGCMutexPool.empty())
    +    ctx.dynDbgGCMutexPool = std::vector<std::mutex>(ctx.arg.threadCount);
    +
       if constexpr (!TrackWhyLive) {
         markParallel();
         return;
    @@ -504,6 +502,25 @@ void MarkLive<ELFT, TrackWhyLive>::mark() {
         for (const typename ELFT::Crel &rel : rels.crels)
           resolveReloc(sec, rel, false);
     
    +    if (ctx.hasDynDbg) {
    +      if (InputSection *is = dyn_cast<InputSection>(&sec)) {
    +        if (const DynDbgGCInfo *gi = is->getDynDbgGCInfo()) {
    +          ctx.dynDbgGCRoots.append(gi->roots);
    +
    +          for (Symbol *sym : gi->refs) {
    +            sym->setFlags(USED);
    +            if (auto *ss = dyn_cast<SharedSymbol>(sym)) {
    +              if (!ss->isWeak())
    +                whyLive.try_emplace(sym, LiveReason{is, "dynamic debugging"});
    +            } else if (auto *d = dyn_cast<Defined>(sym)) {
    +              if (auto *isec = dyn_cast_or_null<InputSectionBase>(d->section))
    +                enqueue(isec, d->value, sym, {is, "dynamic debugging"});
    +            }
    +          }
    +        }
    +      }
    +    }
    +
         for (InputSectionBase *isec : sec.dependentSections)
           enqueue(isec, /*offset=*/0, /*sym=*/nullptr,
                   {&sec, "depended on by section"});
    @@ -524,7 +541,17 @@ static void processSectionEdges(
         Ctx &ctx, InputSectionBase &sec,
         const DenseMap<StringRef, SmallVector<InputSectionBase *, 0>>
             &cNamedSections,
    -    Fn fn) {
    +    SmallVector<StringRef, 0> &ddGCRoots, Fn fn) {
    +  auto markIfSectionPiece = [&](auto *isec, uint64_t offset) {
    +    if (auto *ms = dyn_cast<MergeInputSection>(isec)) {
    +      auto &piece = ms->getSectionPiece(offset);
    +      auto *word =
    +          reinterpret_cast<std::atomic<uint32_t> *>(&piece.inputOff + 1);
    +      constexpr uint32_t liveBit = sys::IsBigEndianHost ? (1U << 31) : 1U;
    +      word->fetch_or(liveBit, std::memory_order_relaxed);
    +    }
    +  };
    +
       auto resolveEdge = [&](const auto &rel) {
         Symbol &sym = sec.file->getRelocTargetSym(rel);
         if (!sym.hasFlag(USED))
    @@ -538,13 +565,7 @@ static void processSectionEdges(
                   ms && offset >= ms->content().size())
                 return;
             }
    -        if (auto *ms = dyn_cast<MergeInputSection>(relSec)) {
    -          auto &piece = ms->getSectionPiece(offset);
    -          auto *word =
    -              reinterpret_cast<std::atomic<uint32_t> *>(&piece.inputOff + 1);
    -          constexpr uint32_t liveBit = sys::IsBigEndianHost ? (1U << 31) : 1U;
    -          word->fetch_or(liveBit, std::memory_order_relaxed);
    -        }
    +        markIfSectionPiece(relSec, offset);
             fn(relSec, offset);
           }
           return;
    @@ -563,6 +584,26 @@ static void processSectionEdges(
         fn(isec, 0);
       if (sec.nextInSectionGroup)
         fn(sec.nextInSectionGroup, 0);
    +
    +  if (ctx.hasDynDbg) {
    +    if (InputSection *is = dyn_cast<InputSection>(&sec)) {
    +    ...
    [truncated]
    
    
    ``````

    </details>

    smithp35 smithp35 commented on Oct 23, 2026 16:49 UTC
    Contributor

    Apologies for the delay in responding. I'm finding this a tough one to review. Will try and spend some time next week.

    My initial reaction is that this is quite complicated, particularly for a niche feature.

    I'm wondering if there's a way of simplifying it, possibly at the expense of maximum performance. For example instead of lazily scanning the embedded ELF and then updating all sections referenced from it with an embedded pointer, could there be a pre-GC step that populates the necessary information? I'm also wondering if the additional information can be stored externally to the InputSection. It would mean looking it up when needed, but would also limit the impact on programs that does not use dynamic debug.

    Will see if I can come up with any concrete suggestions next week.

    I expect MaskRay will have better ideas than I have, having recently changed the MarkLive code.

    nga888 nga888 commented on Oct 23, 2026 16:59 UTC
    Author

    Apologies for the delay in responding. I'm finding this a tough one to review. Will try and spend some time next week.

    No problem. Yes, it is a bit of a "tough" one.

    My initial reaction is that this is quite complicated, particularly for a niche feature.

    I've tried my best to keep it "simple" and I'm open to suggestions to minimise impact. I did consider using a lookup rather than modifying InputSection, but it was "only" an additional pointer, so I thought that might be OK. Performance isn't critical but at the same time the overheads are already quite high for dynamic debugging, so ideally wouldn't want it to be even slower.

    smithp35 smithp35 commented on code on Oct 26, 2026 13:50 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -1197,6 +1198,30 @@ InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
       return makeThreadLocal<InputSection>(*this, sec, name);
     }
     
    +template <typename ELFT>
    +void ObjFile<ELFT>::visitGlobalRelocSymbolIndices(

    From what I can tell, only firstGlobal is used from this. Could that be passed in as a parameter so this could be a static function in InputFile.cpp

    It would also help distinguish between the LLD Object file (this) and ELFFile obj, by using a parameter it is clear that only one of these is involved.

    Alternatively obj could be obtained from This using getObj() that would at least make sure that the ObjFile and ELFFile match.

    smithp35 smithp35 commented on code on Oct 26, 2026 15:06 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the
    +// GC roots for the "inner" `--gc-sections` mark live.
    +template <typename ELFT> void ObjFile<ELFT>::maybeCreateDynDbgGCInfo() {
    +  if (!dynDbgInfo || dynDbgInfo->gcInfoCreated || !dynDbgInfo->elf)
    +    return;
    +
    +  LockGuard lock(this, ctx.dynDbgGCMutexPool);
    +  if (dynDbgInfo->gcInfoCreated)
    +    return;
    +
    +  auto *symtab = ctx.symtab.get();
    +  auto &dbgObj = cast<ObjFile<ELFT>>(*(dynDbgInfo->elf));
    +  const object::ELFFile<ELFT> obj = dbgObj.getObj();
    +  ArrayRef<Elf_Shdr> dbgShdrs = dbgObj.template getELFShdrs<ELFT>();
    +  uint32_t numDbgShdrs = dbgShdrs.size();
    +
    +  // Used to record a section's relocation section index and whether the section
    +  // has already been processed.
    +  struct SecInfo {
    +    uint32_t relocIdx;
    +    bool processed;
    +  };
    +  SmallVector<SecInfo, 0> secInfos(numDbgShdrs);
    +
    +  // Populate relocation section indices and any extended symbol index table.
    +  for (uint32_t secIdx = 1; secIdx < numDbgShdrs; ++secIdx) {
    +    const Elf_Shdr &sh = dbgShdrs[secIdx];
    +    if (isStaticRelSecType(sh.sh_type))
    +      secInfos[sh.sh_info].relocIdx = secIdx;
    +    else if (sh.sh_type == SHT_SYMTAB_SHNDX)
    +      dbgObj.shndxTable = CHECK2(obj.getSHNDXTable(sh, dbgShdrs), &dbgObj);
    +  }
    +
    +  ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getELFSyms<ELFT>();
    +  for (uint32_t i = dbgObj.firstGlobal, end = dbgSyms.size(); i != end; ++i) {
    +    const Elf_Sym &s = dbgSyms[i];
    +    uint32_t secIdx = s.st_shndx;
    +    if (secIdx == SHN_UNDEF)
    +      continue;
    +
    +    if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
    +      secIdx =
    +          check(getExtendedSymbolTableIndex<ELFT>(s, i, dbgObj.shndxTable));
    +    else if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE))
    +      continue;
    +
    +    SecInfo &si = secInfos[secIdx];
    +    if (si.processed)
    +      continue;
    +
    +    // Only interested in dynamic debugging "inner" `__dyndbg.` prefixed
    +    // symbols.
    +    StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +    if (!name.starts_with("__dyndbg."))
    +      continue;
    +
    +    si.processed = true;

    IIUC we only need to find one __dyndbg. symbol per section, as we add the references from the section (not the symbol) and we only need one GC root for the section?

    If so, could be worth a comment. Something like:
    `` Only one GC root is required per section.``

    smithp35 smithp35 commented on code on Oct 26, 2026 15:07 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the
    +// GC roots for the "inner" `--gc-sections` mark live.
    +template <typename ELFT> void ObjFile<ELFT>::maybeCreateDynDbgGCInfo() {
    +  if (!dynDbgInfo || dynDbgInfo->gcInfoCreated || !dynDbgInfo->elf)
    +    return;
    +
    +  LockGuard lock(this, ctx.dynDbgGCMutexPool);
    +  if (dynDbgInfo->gcInfoCreated)
    +    return;
    +
    +  auto *symtab = ctx.symtab.get();
    +  auto &dbgObj = cast<ObjFile<ELFT>>(*(dynDbgInfo->elf));
    +  const object::ELFFile<ELFT> obj = dbgObj.getObj();
    +  ArrayRef<Elf_Shdr> dbgShdrs = dbgObj.template getELFShdrs<ELFT>();
    +  uint32_t numDbgShdrs = dbgShdrs.size();
    +
    +  // Used to record a section's relocation section index and whether the section
    +  // has already been processed.
    +  struct SecInfo {
    +    uint32_t relocIdx;
    +    bool processed;
    +  };
    +  SmallVector<SecInfo, 0> secInfos(numDbgShdrs);
    +
    +  // Populate relocation section indices and any extended symbol index table.
    +  for (uint32_t secIdx = 1; secIdx < numDbgShdrs; ++secIdx) {
    +    const Elf_Shdr &sh = dbgShdrs[secIdx];
    +    if (isStaticRelSecType(sh.sh_type))
    +      secInfos[sh.sh_info].relocIdx = secIdx;
    +    else if (sh.sh_type == SHT_SYMTAB_SHNDX)
    +      dbgObj.shndxTable = CHECK2(obj.getSHNDXTable(sh, dbgShdrs), &dbgObj);
    +  }
    +
    +  ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getELFSyms<ELFT>();
    +  for (uint32_t i = dbgObj.firstGlobal, end = dbgSyms.size(); i != end; ++i) {
    +    const Elf_Sym &s = dbgSyms[i];
    +    uint32_t secIdx = s.st_shndx;
    +    if (secIdx == SHN_UNDEF)
    +      continue;
    +
    +    if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
    +      secIdx =
    +          check(getExtendedSymbolTableIndex<ELFT>(s, i, dbgObj.shndxTable));
    +    else if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE))
    +      continue;
    +
    +    SecInfo &si = secInfos[secIdx];
    +    if (si.processed)
    +      continue;
    +
    +    // Only interested in dynamic debugging "inner" `__dyndbg.` prefixed
    +    // symbols.
    +    StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +    if (!name.starts_with("__dyndbg."))
    +      continue;
    +
    +    si.processed = true;
    +
    +    // Try to find the matching "outer" symbol.
    +    Symbol *sym = symtab->find(name.drop_front(9));
    +    if (!sym || !sym->isDefined() || sym->file != this)
    +      continue;
    +
    +    InputSection *is = dyn_cast<InputSection>(cast<Defined>(sym)->section);
    +    if (!is)
    +      continue;
    +
    +    assert(is->file == this);
    +
    +    // Get or create the InputSection's DynDbgGCInfo.
    +    DynDbgGCInfo *gcInfo = is->dynDbgGCInfo;
    +    if (!gcInfo) {
    +      gcInfo = new DynDbgGCInfo;
    +      dynDbgInfo->gcInfos.emplace_back(std::unique_ptr<DynDbgGCInfo>(gcInfo));
    +      is->dynDbgGCInfo = gcInfo;
    +    }
    +
    +    // Add this "inner" `__dyndbg.` prefixed symbol as a GC root.

    Can we add as a GC root for the inner object.

    smithp35 smithp35 commented on code on Oct 26, 2026 15:11 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the
    +// GC roots for the "inner" `--gc-sections` mark live.
    +template <typename ELFT> void ObjFile<ELFT>::maybeCreateDynDbgGCInfo() {
    +  if (!dynDbgInfo || dynDbgInfo->gcInfoCreated || !dynDbgInfo->elf)
    +    return;
    +
    +  LockGuard lock(this, ctx.dynDbgGCMutexPool);
    +  if (dynDbgInfo->gcInfoCreated)
    +    return;
    +
    +  auto *symtab = ctx.symtab.get();
    +  auto &dbgObj = cast<ObjFile<ELFT>>(*(dynDbgInfo->elf));
    +  const object::ELFFile<ELFT> obj = dbgObj.getObj();
    +  ArrayRef<Elf_Shdr> dbgShdrs = dbgObj.template getELFShdrs<ELFT>();
    +  uint32_t numDbgShdrs = dbgShdrs.size();
    +
    +  // Used to record a section's relocation section index and whether the section
    +  // has already been processed.
    +  struct SecInfo {
    +    uint32_t relocIdx;
    +    bool processed;
    +  };
    +  SmallVector<SecInfo, 0> secInfos(numDbgShdrs);
    +
    +  // Populate relocation section indices and any extended symbol index table.
    +  for (uint32_t secIdx = 1; secIdx < numDbgShdrs; ++secIdx) {
    +    const Elf_Shdr &sh = dbgShdrs[secIdx];
    +    if (isStaticRelSecType(sh.sh_type))
    +      secInfos[sh.sh_info].relocIdx = secIdx;
    +    else if (sh.sh_type == SHT_SYMTAB_SHNDX)
    +      dbgObj.shndxTable = CHECK2(obj.getSHNDXTable(sh, dbgShdrs), &dbgObj);
    +  }
    +
    +  ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getELFSyms<ELFT>();
    +  for (uint32_t i = dbgObj.firstGlobal, end = dbgSyms.size(); i != end; ++i) {
    +    const Elf_Sym &s = dbgSyms[i];
    +    uint32_t secIdx = s.st_shndx;
    +    if (secIdx == SHN_UNDEF)
    +      continue;
    +
    +    if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
    +      secIdx =
    +          check(getExtendedSymbolTableIndex<ELFT>(s, i, dbgObj.shndxTable));
    +    else if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE))
    +      continue;
    +
    +    SecInfo &si = secInfos[secIdx];
    +    if (si.processed)
    +      continue;
    +
    +    // Only interested in dynamic debugging "inner" `__dyndbg.` prefixed
    +    // symbols.
    +    StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +    if (!name.starts_with("__dyndbg."))
    +      continue;
    +
    +    si.processed = true;
    +
    +    // Try to find the matching "outer" symbol.
    +    Symbol *sym = symtab->find(name.drop_front(9));
    +    if (!sym || !sym->isDefined() || sym->file != this)
    +      continue;
    +
    +    InputSection *is = dyn_cast<InputSection>(cast<Defined>(sym)->section);
    +    if (!is)
    +      continue;
    +
    +    assert(is->file == this);
    +
    +    // Get or create the InputSection's DynDbgGCInfo.
    +    DynDbgGCInfo *gcInfo = is->dynDbgGCInfo;
    +    if (!gcInfo) {
    +      gcInfo = new DynDbgGCInfo;
    +      dynDbgInfo->gcInfos.emplace_back(std::unique_ptr<DynDbgGCInfo>(gcInfo));
    +      is->dynDbgGCInfo = gcInfo;
    +    }
    +
    +    // Add this "inner" `__dyndbg.` prefixed symbol as a GC root.
    +    gcInfo->roots.push_back(name);
    +
    +    if (!si.relocIdx)
    +      continue;
    +
    +    // Find "outer" symbols referenced by the "inner" and record in the

    Can we use by the "inner" section and record ... to make it clear that all symbols in the section defining __dyndbg.<fn> are added as references.

    smithp35 smithp35 commented on code on Oct 26, 2026 15:14 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and

    I think it would be useful to say "inner object"

    smithp35 smithp35 commented on code on Oct 26, 2026 15:24 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the

    From what I can tell only one __dyndbg. prefixed symbol is recorded as a GC root per section. If I'm right, perhaps say something like:
    `` One __dyndbg. prefixed symbol per "inner" section is recorded as a GC root for each "outer" InputSection.``

    smithp35 smithp35 commented on code on Oct 26, 2026 15:30 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the

    I found the sentence starting with These GC roots difficult to read. Perhaps (assuming I understood it right)
    `` During MarkLive for the "outer" ELF file each live "outer" InputSection appends its "inner" GC roots to form the GC roots for the "inner" --gc-sections` MarkLive.

    smithp35 smithp35 commented on code on Oct 26, 2026 15:39 UTC
    Code Review
    lld/ELF/Config.h:1
    @@ -801,6 +801,11 @@ struct Ctx : CommonLinkerContext {
       // Pointer to the output of the embedded unoptimized dynamic debugging
       // relocatable link.
       std::unique_ptr<llvm::FileOutputBuffer> dynDbgOutput;
    +  // GC roots for the dynamic debugging relocatable link.
    +  SmallVector<llvm::StringRef, 0> dynDbgGCRoots;

    could we call this innerDynDbgGCRoots it would then be obvious at the call site that these were for the inner object.

    smithp35 smithp35 commented on code on Oct 26, 2026 16:17 UTC
    Code Review
    lld/ELF/MarkLive.cpp:1
    @@ -504,6 +502,25 @@ void MarkLive<ELFT, TrackWhyLive>::mark() {
         for (const typename ELFT::Crel &rel : rels.crels)
           resolveReloc(sec, rel, false);
     
    +    if (ctx.hasDynDbg) {

    Could be worth extracting

    if (ctx.hasDynDbg) {
      if (InputSection *is = dyn_cast<InputSection>(&sec)) {
        if (const DynDbgGCInfo *gi = is->getDynDbgGCInfo())
    

    Into a function called something like getDynDbgGCInfo(InputSectionBase&) at the two call sites that could save a couple of levels of indenting.
    if (const DynDbgGCInfo *gi = getDynDbgGCInfo(&sec)) {
    ...
    }
    

    smithp35 smithp35 commented on Oct 26, 2026 16:40 UTC
    Reviewer

    To check my understanding:
    The LockGuard (pool of mutexes) is to prevent an inner ELF from being processed twice by more than one thread (via reaching the same section).
    The "inner" ELF file via the __dyndbg.fn can only add dynDbgGCInfo to InputSections of the corresponding outer ELF file. Therefore the lock on the inner ELF file is sufficient.

  • The dynDbgGCInfo for an "inner" ELF file is read-only and cached.
  • To suggest an alternative design, would it be possible to do a parallelForEach over ctx.objectFiles to populate the dynDbgGCInfo early in markLive()? I think that would mean you wouldn't need the LockGuard and the ctx.dynDbgGCMutexPool. That would mean that within the MarkLive processing we can concentrate on following edges and collecting the GC Roots for the "inner" object without having to understand the side-effects of the lazy processing.

    Before doing a lot of work it would be good to get @MaskRay 's opinion on the design? I don't want to waste your time if he has a different opinion.

    nga888 nga888 commented on Oct 26, 2026 17:19 UTC
    Author

    To check my understanding:

    > The LockGuard (pool of mutexes) is to prevent an inner ELF from being processed twice by more than one thread (via reaching the same section).

    Yes.

    The "inner" ELF file via the __dyndbg.fn can only add dynDbgGCInfo to InputSections of the corresponding outer ELF file. Therefore the lock on the inner ELF file is sufficient.

    Yes, the "inner" __dyndbg. prefixed symbols are closely coupled to the corresponding "outer" ELF.

    * The dynDbgGCInfo for an "inner" ELF file is read-only and cached.

    dynDbgGCInfo is not used for the "inner" ELF InputSections. It's only the dynDbgGCInfo "roots" from the "outer" ELF InputSections that are indirectly used for the "inner" ELF during it's markLive().

    To suggest an alternative design, would it be possible to do a parallelForEach over ctx.objectFiles to populate the dynDbgGCInfo early in markLive()? I think that would mean you wouldn't need the LockGuard and the ctx.dynDbgGCMutexPool.

    Yes, this should be possible but I decided on the "lazy" approach so that only objects that are needed are processed. However, how worthwhile this approach might be is hard to quantify and will be very dependent on the nature of the link.

    nga888 nga888 commented on code on Oct 26, 2026 17:25 UTC
    Code Review
    lld/ELF/Config.h:1
    @@ -801,6 +801,11 @@ struct Ctx : CommonLinkerContext {
       // Pointer to the output of the embedded unoptimized dynamic debugging
       // relocatable link.
       std::unique_ptr<llvm::FileOutputBuffer> dynDbgOutput;
    +  // GC roots for the dynamic debugging relocatable link.
    +  SmallVector<llvm::StringRef, 0> dynDbgGCRoots;

    I'll probably go with dynDbgInnerGCRoots.

    nga888 nga888 commented on code on Oct 26, 2026 17:35 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -1197,6 +1198,30 @@ InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
       return makeThreadLocal<InputSection>(*this, sec, name);
     }
     
    +template <typename ELFT>
    +void ObjFile<ELFT>::visitGlobalRelocSymbolIndices(

    Yes, it's only firstGlobal and this that are used, and the convenience of the ELFT types. But it should be possible to go static, or as you've also suggested using getObj(). I think I ended up with this because of concerns over getObj() overhead, which actually doesn't look to be so bad. I'll experiment and see what looks better.

    nga888 nga888 commented on code on Oct 26, 2026 17:40 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the

    Unfortunately, there can be more that one "inner" GC root per "outer" InputSection. This can occur when linking dynamic debug objects that have been combined using a relocatable link. But yes, in the "normal" use case, there's just 1. I'll add this info to this comment.

    nga888 nga888 commented on code on Oct 26, 2026 17:41 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the

    I'll try to re-phrase to make it easy to read and understand.

    nga888 nga888 commented on code on Oct 26, 2026 17:45 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2063,136 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the object and
    +// records the references to optimized "outer" symbols in the DynDbgGCInfo
    +// attached to the InputSection containing the optimized "outer" equivalent
    +// symbol. These DynDbgGCInfo references become additional dependencies for the
    +// "outer" InputSections during the "outer" `--gc-sections` mark live.
    +//
    +// The `__dyndbg.` prefixed symbols are also recorded as GC roots in the
    +// DynDbgGCInfo for the "outer" InputSections. These GC roots are collected for
    +// the live "outer" InputSections during the "outer" mark live and used as the
    +// GC roots for the "inner" `--gc-sections` mark live.
    +template <typename ELFT> void ObjFile<ELFT>::maybeCreateDynDbgGCInfo() {
    +  if (!dynDbgInfo || dynDbgInfo->gcInfoCreated || !dynDbgInfo->elf)
    +    return;
    +
    +  LockGuard lock(this, ctx.dynDbgGCMutexPool);
    +  if (dynDbgInfo->gcInfoCreated)
    +    return;
    +
    +  auto *symtab = ctx.symtab.get();
    +  auto &dbgObj = cast<ObjFile<ELFT>>(*(dynDbgInfo->elf));
    +  const object::ELFFile<ELFT> obj = dbgObj.getObj();
    +  ArrayRef<Elf_Shdr> dbgShdrs = dbgObj.template getELFShdrs<ELFT>();
    +  uint32_t numDbgShdrs = dbgShdrs.size();
    +
    +  // Used to record a section's relocation section index and whether the section
    +  // has already been processed.
    +  struct SecInfo {
    +    uint32_t relocIdx;
    +    bool processed;
    +  };
    +  SmallVector<SecInfo, 0> secInfos(numDbgShdrs);
    +
    +  // Populate relocation section indices and any extended symbol index table.
    +  for (uint32_t secIdx = 1; secIdx < numDbgShdrs; ++secIdx) {
    +    const Elf_Shdr &sh = dbgShdrs[secIdx];
    +    if (isStaticRelSecType(sh.sh_type))
    +      secInfos[sh.sh_info].relocIdx = secIdx;
    +    else if (sh.sh_type == SHT_SYMTAB_SHNDX)
    +      dbgObj.shndxTable = CHECK2(obj.getSHNDXTable(sh, dbgShdrs), &dbgObj);
    +  }
    +
    +  ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getELFSyms<ELFT>();
    +  for (uint32_t i = dbgObj.firstGlobal, end = dbgSyms.size(); i != end; ++i) {
    +    const Elf_Sym &s = dbgSyms[i];
    +    uint32_t secIdx = s.st_shndx;
    +    if (secIdx == SHN_UNDEF)
    +      continue;
    +
    +    if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
    +      secIdx =
    +          check(getExtendedSymbolTableIndex<ELFT>(s, i, dbgObj.shndxTable));
    +    else if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE))
    +      continue;
    +
    +    SecInfo &si = secInfos[secIdx];
    +    if (si.processed)
    +      continue;
    +
    +    // Only interested in dynamic debugging "inner" `__dyndbg.` prefixed
    +    // symbols.
    +    StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +    if (!name.starts_with("__dyndbg."))
    +      continue;
    +
    +    si.processed = true;

    Yes, the references are from the entire "inner" section and we only need the one GC root from the "inner" section. However, as mentioned above, multiple "inner" sections can map to a single "outer" InputSection. So probably a comment on the lines of:

    // Only one "inner" GC root is required per "inner" section.

    nga888 nga888 commented on Oct 30, 2026 01:24 UTC
    Author

    Ping @MaskRay

    nga888 nga888 commented on Nov 06, 2026 17:46 UTC
    Author

    Ping.

    MaskRay MaskRay commented on Nov 06, 2026 18:24 UTC
    Contributor

    Ping.

    Sorry for the belated response. Will read.

    MaskRay MaskRay commented on code on Nov 09, 2026 05:05 UTC
    Code Review
    lld/ELF/InputFiles.cpp:1
    @@ -2047,6 +2066,142 @@ std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
       return std::string(path);
     }
     
    +DynDbgInfo::DynDbgInfo(InputSection *is) : inputSec(is) { assert(is); }
    +
    +namespace {
    +// LockGuard takes ownership of a mutex from a pool of mutexes based on the hash
    +// of the address of the object being locked. This means that each object does
    +// not need to have its own mutex but at the potential cost of more lock
    +// contention.
    +struct LockGuard {
    +  std::mutex *mutex;
    +
    +  LockGuard(const void *ptr, std::vector<std::mutex> &mutexPool) {
    +    assert(!mutexPool.empty());
    +    mutex = &mutexPool[hash_value(ptr) % mutexPool.size()];
    +    mutex->lock();
    +  }
    +  ~LockGuard() { mutex->unlock(); }
    +};
    +} // namespace
    +
    +// Scans the unoptimized "inner" `__dyndbg.` prefixed symbols of the "inner"
    +// object and records the "inner" section references to optimized "outer"
    +// symbols in the DynDbgGCInfo attached to the InputSection containing the
    +// optimized "outer" equivalent symbol. These DynDbgGCInfo references become
    +// additional dependencies for the "outer" InputSections during the "outer"
    +// `--gc-sections` mark live.
    +//
    +// One `__dyndbg.` prefixed symbol per "inner" section is recorded as an "inner"
    +// GC root in the DynDbgGCInfo of the corresponding "outer" InputSection.
    +// Usually, each "outer" InputSection will have 1 "inner" GC root. However, it
    +// is possible to have multiple when linking dynamic debug objects that have
    +// been combined in a relocatable link. During the "outer" `--gc-sections` mark
    +// live, each live "outer" InputSection appends its "inner" GC roots to form all
    +// the GC roots for the "inner" `--gc-sections` mark live.
    +template <typename ELFT> void ObjFile<ELFT>::maybeCreateDynDbgGCInfo() {
    +  if (!dynDbgInfo || dynDbgInfo->gcInfoCreated || !dynDbgInfo->elf)
    +    return;
    +
    +  LockGuard lock(this, ctx.dynDbgGCMutexPool);
    +  if (dynDbgInfo->gcInfoCreated)
    +    return;
    +
    +  auto *symtab = ctx.symtab.get();
    +  auto &dbgObj = cast<ObjFile<ELFT>>(*(dynDbgInfo->elf));
    +  const object::ELFFile<ELFT> obj = dbgObj.getObj();
    +  ArrayRef<Elf_Shdr> dbgShdrs = dbgObj.template getELFShdrs<ELFT>();
    +  uint32_t numDbgShdrs = dbgShdrs.size();
    +
    +  // Used to record a section's relocation section index and whether the section
    +  // has already been processed.
    +  struct SecInfo {
    +    uint32_t relocIdx;
    +    bool processed;
    +  };
    +  SmallVector<SecInfo, 0> secInfos(numDbgShdrs);
    +
    +  // Populate relocation section indices and any extended symbol index table.
    +  for (uint32_t secIdx = 1; secIdx < numDbgShdrs; ++secIdx) {
    +    const Elf_Shdr &sh = dbgShdrs[secIdx];
    +    if (isStaticRelSecType(sh.sh_type))
    +      secInfos[sh.sh_info].relocIdx = secIdx;
    +    else if (sh.sh_type == SHT_SYMTAB_SHNDX)
    +      dbgObj.shndxTable = CHECK2(obj.getSHNDXTable(sh, dbgShdrs), &dbgObj);
    +  }
    +
    +  ArrayRef<Elf_Sym> dbgSyms = dbgObj.template getELFSyms<ELFT>();
    +  for (uint32_t i = dbgObj.firstGlobal, end = dbgSyms.size(); i != end; ++i) {
    +    const Elf_Sym &s = dbgSyms[i];
    +    uint32_t secIdx = s.st_shndx;
    +    if (secIdx == SHN_UNDEF)
    +      continue;
    +
    +    if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
    +      secIdx =
    +          check(getExtendedSymbolTableIndex<ELFT>(s, i, dbgObj.shndxTable));
    +    else if (LLVM_UNLIKELY(secIdx >= SHN_LORESERVE))
    +      continue;
    +
    +    SecInfo &si = secInfos[secIdx];
    +    if (si.processed)
    +      continue;
    +
    +    // Only interested in dynamic debugging "inner" `__dyndbg.` prefixed
    +    // symbols.
    +    StringRef name = CHECK2(s.getName(dbgObj.stringTable), this);
    +    if (!name.starts_with("__dyndbg."))
    +      continue;
    +
    +    // Only one "inner" GC root is required per "inner" section.
    +    si.processed = true;
    +
    +    // Try to find the matching "outer" symbol.
    +    Symbol *sym = symtab->find(name.drop_front(9));

    starts_with("__dyndbg.") + drop_front(9) => consume_front("__dyndbg.")

    MaskRay MaskRay commented on Nov 09, 2026 06:06 UTC
    Contributor

    Instead of summarizing the inner graph, I suggest adding it to the outer GC graph:

    With --gc-sections, keep the inner object that initDynDbgSymbols already parses. In postParse, create its SHF_ALLOC sections (never output) and fill its symbol table: undefined globals are the outer symbols, and __dyndbg.X becomes a Defined that is not inserted into the symbol table.
    Add the inner section defining __dyndbg.X to the dependentSections of the section defining X.
    The existing mark then follows inner relocations transitively and sets USED on every target, undefined ones included. MarkLive::run additionally scans inner .eh_frame for LSDAs.
    Pass the indices of the inner sections found live to the inner link as its GC roots.

    This removes DynDbgGCInfo, the new InputSection member, maybeCreateDynDbgGCInfo and the ekind switch, the mutex pool and the atomic, and the changes to both mark paths. The normal (non-dynamic-debugging) path pays a null check per file.

    I have a prototype at https://github.com/MaskRay/llvm-project/tree/dyn-dbg-gc-nodes . It changes lld/ELF by +106/-18 compared with +332/-62 here, and adds dynamic-debug-gc-sections.test, which covers the a few cases (it fails with this patch).

    Two other things:

    The !ctx.dynDbgRelocatable in markUsed is needed: without it, markUsedSymbols retains symbols referenced only by non-SHF_ALLOC inner sections (undef_used_by_non_alloc via .debug_xyz). Please add a comment.
    With --gc-sections, the inner link drops .eh_frame. In a -r link .eh_frame is a regular section that nothing references; plain ld.lld -r --gc-sections behaves the same. The embedded object therefore loses its unwind information, with this patch and with the prototype. Is that acceptable for the debugger? If not, the inner link needs to handle .eh_frame the way a final link does and drop the FDEs of dead functions.

    nga888 nga888 commented on Nov 16, 2026 11:51 UTC
    Author

    @MaskRay, thanks for the review. I've been away on PTO but will get back to this soon and evaluate your suggestions.

    nga888 nga888 commented on Nov 27, 2026 12:45 UTC
    Author

    @MaskRay, thanks for the review. I've been away on PTO but will get back to this soon and evaluate your suggestions.

    Just wanted to post a quick update. I've been busy with other tasks since coming back from PTO. I've only managed to do a quick evaluation on Windows and your suggested approach has slightly higher overhead in terms of execution time and memory usage. It also has revealed an issue relating to COMDATs. However, it's definitely more concise and straightforward than my patch! I need to spend some more time on this and hope to have more feedback soon.

    Reviewers
    Assignees
    nga888 nga888
    Labels
    risk: low confidence: 88.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 60.4% (MEDIUM) · Higher = larger blast radius
    60.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.6% · Lower = rushed or shallow review
    88.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.9% · Safe to merge
    6.9%