[llvm-branch-commits] [llvm] [llvm-objcopy] Stream ELF output to reduce peak memory usage (PR #217706)

James Henderson via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Tue Oct 13 02:08:34 PDT 2026


================
@@ -2084,40 +2151,32 @@ template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
     Ehdr.e_shnum = 0;
     Ehdr.e_shstrndx = 0;
   }
+  writeObject(Output->streamAt(0), Ehdr);
 }
 
 template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
-  for (auto &Seg : Obj.segments())
-    writePhdr(Seg);
+  if (Obj.segments().empty())
+    return;
+  raw_ostream &Out = Output->streamAt(Obj.ProgramHdrSegment.Offset);
+  for (const Segment &Seg : Obj.segments())
+    writePhdr(Out, Seg);
 }
 
 template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
-  // This reference serves to write the dummy section header at the begining
-  // of the file. It is not used for anything else
-  Elf_Shdr &Shdr =
-      *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
-  Shdr.sh_name = 0;
+  raw_ostream &Out = Output->streamAt(Obj.SHOff);
+  Elf_Shdr Shdr = {};
   Shdr.sh_type = SHT_NULL;
----------------
jh7370 wrote:

Aside: arguably, this line is superfluous too, since SHT_NULL is 0, but I prefer to keep it there to be help it be explicit.

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


More information about the llvm-branch-commits mailing list