@@ -344,9 +344,10 @@ template <class ELFT> void OutputSection::maybeCompress() {
344344 (void )sizeof (Elf_Chdr);
345345
346346 DebugCompressionType ctype = DebugCompressionType::None;
347+ size_t compressedSize = sizeof (Elf_Chdr);
347348 unsigned level = 0 ; // default compression level
348349 if (!(flags & SHF_ALLOC) && config->compressDebugSections &&
349- name.starts_with (" .debug_" ) && size )
350+ name.starts_with (" .debug_" ))
350351 ctype = *config->compressDebugSections ;
351352 for (auto &[glob, t, l] : config->compressSections )
352353 if (glob.match (name))
@@ -360,7 +361,6 @@ template <class ELFT> void OutputSection::maybeCompress() {
360361 }
361362
362363 llvm::TimeTraceScope timeScope (" Compress sections" );
363- compressed.uncompressedSize = size;
364364 auto buf = std::make_unique<uint8_t []>(size);
365365 // Write uncompressed data to a temporary zero-initialized buffer.
366366 {
@@ -378,7 +378,6 @@ template <class ELFT> void OutputSection::maybeCompress() {
378378 [[maybe_unused]] constexpr size_t shardSize = 1 << 20 ;
379379 auto shardsIn = split (ArrayRef<uint8_t >(buf.get (), size), shardSize);
380380 const size_t numShards = shardsIn.size ();
381- compressed.numShards = numShards;
382381 auto shardsOut = std::make_unique<SmallVector<uint8_t , 0 >[]>(numShards);
383382
384383#if LLVM_ENABLE_ZSTD
@@ -409,9 +408,8 @@ template <class ELFT> void OutputSection::maybeCompress() {
409408 shardsOut[i] = std::move (out);
410409 });
411410 compressed.type = ELFCOMPRESS_ZSTD;
412- size = sizeof (Elf_Chdr);
413411 for (size_t i = 0 ; i != numShards; ++i)
414- size += shardsOut[i].size ();
412+ compressedSize += shardsOut[i].size ();
415413 }
416414#endif
417415
@@ -434,18 +432,23 @@ template <class ELFT> void OutputSection::maybeCompress() {
434432
435433 // Update section size and combine Alder-32 checksums.
436434 uint32_t checksum = 1 ; // Initial Adler-32 value
437- size = sizeof (Elf_Chdr) + 2 ; // Elf_Chdir and zlib header
435+ compressedSize += 2 ; // Elf_Chdir and zlib header
438436 for (size_t i = 0 ; i != numShards; ++i) {
439- size += shardsOut[i].size ();
437+ compressedSize += shardsOut[i].size ();
440438 checksum = adler32_combine (checksum, shardsAdler[i], shardsIn[i].size ());
441439 }
442- size += 4 ; // checksum
440+ compressedSize += 4 ; // checksum
443441 compressed.type = ELFCOMPRESS_ZLIB;
444442 compressed.checksum = checksum;
445443 }
446444#endif
447445
446+ if (compressedSize >= size)
447+ return ;
448+ compressed.uncompressedSize = size;
448449 compressed.shards = std::move (shardsOut);
450+ compressed.numShards = numShards;
451+ size = compressedSize;
449452 flags |= SHF_COMPRESSED;
450453}
451454
0 commit comments