[llvm] [llvm-objcopy][COFF] Update WinCFGuard section contents after stripping (PR #153322)

Martin Storsjö via llvm-commits llvm-commits at lists.llvm.org
Thu Aug 14 05:52:31 PDT 2025


================
@@ -92,6 +93,63 @@ Error COFFWriter::finalizeSymbolContents() {
   return Error::success();
 }
 
+Error COFFWriter::finalizeCFGuardContents() {
+  DenseMap<size_t, size_t> SymIdMap;
+  bool NeedUpdate = false;
+  for (Symbol &Sym : Obj.getMutableSymbols()) {
+    NeedUpdate |= Sym.OriginalRawIndex == Sym.RawIndex;
+    SymIdMap[Sym.OriginalRawIndex] = Sym.RawIndex;
+  }
+
+  if (!NeedUpdate)
+    return Error::success();
+
+  for (auto &Sym : Obj.getMutableSymbols()) {
+    if (Sym.Name != ".gljmp$y" && Sym.Name != ".giats$y" &&
+        Sym.Name != ".gfids$y")
+      continue;
+
+    auto Sec = find_if(Obj.getMutableSections(),
+                       [&Sym](Section &S) { return S.Name == Sym.Name; });
+
+    if (Sec == Obj.getMutableSections().end() ||
+        Sec->UniqueId != Sym.TargetSectionId)
+      return createStringError(object_error::invalid_symbol_index,
+                               "symbol '%s' is missing its section",
+                               Sym.Name.str().c_str());
+
+    if (Sym.Sym.NumberOfAuxSymbols != 1 ||
+        Sym.Sym.StorageClass != IMAGE_SYM_CLASS_STATIC)
+      return createStringError(object_error::invalid_symbol_index,
+                               "symbol '%s' has unexpected section format",
+                               Sym.Name.str().c_str());
+
+    ArrayRef<uint8_t> RawIds = Sec->getContents();
+    // Nothing to do and also CheckSum will be -1 instead of 0 if we recalculate
+    // it on empty input.
+    if (RawIds.size() == 0)
+      return Error::success();
+
+    // Create updated content
+    ArrayRef<uint32_t> Ids(reinterpret_cast<const uint32_t *>(RawIds.data()),
+                           RawIds.size() / 4);
+    std::vector<uint32_t> NewIds;
+    for (auto Id : Ids)
+      NewIds.push_back(SymIdMap[Id]);
----------------
mstorsjo wrote:

Silently leaving it as is would be bad, as it would essentially be a broken object file - as you say the linker would then complain about it later.

I guess ideally, if these sections simply are listings of symbols, and some of those symbols no longer exist, then we should just remove them from the listings. That would then require shrinking the section contents.

Initially it's probably fine to just error out on this case, but in the theoretical best case I guess we'd drop them from the listing.

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


More information about the llvm-commits mailing list