Index: ELF/Writer.cpp =================================================================== --- ELF/Writer.cpp +++ ELF/Writer.cpp @@ -2189,21 +2189,19 @@ memcpy(I, &Target->TrapInstr, 4); } -// Fill the last page of executable segments with trap instructions -// instead of leaving them as zero. Even though it is not required by any -// standard, it is in general a good thing to do for security reasons. -// -// We'll leave other pages in segments as-is because the rest will be -// overwritten by output sections. +// Fill the executable segments with trap instructions instead of leaving them +// as zero. Even though it is not required by any standard, it is in general a +// good thing to do for security reasons. We have to fill all pages to properly +// fill paddings created during applying alignment to sections. template void Writer::writeTrapInstr() { if (Script->HasSectionsCommand) return; - // Fill the last page. + // Fill executable segments with trap instructions. uint8_t *Buf = Buffer->getBufferStart(); for (PhdrEntry *P : Phdrs) if (P->p_type == PT_LOAD && (P->p_flags & PF_X)) - fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize), + fillTrap(Buf + P->p_offset, Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize)); // Round up the file size of the last segment to the page boundary iff it is Index: test/ELF/fill-trap2.s =================================================================== --- test/ELF/fill-trap2.s +++ test/ELF/fill-trap2.s @@ -0,0 +1,27 @@ +# REQUIRES: x86 + +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t +# RUN: ld.lld %t -o %t2 +# RUN: llvm-readobj -program-headers %t2 | FileCheck %s +# RUN: od -Ax -t x1 -N16 -j0x1000 %t2 | FileCheck %s -check-prefix=FILL + +# CHECK: ProgramHeader { +# CHECK: Type: PT_LOAD +# CHECK: Offset: 0x1000 +# CHECK-NEXT: VirtualAddress: +# CHECK-NEXT: PhysicalAddress: +# CHECK-NEXT: FileSize: 8192 +# CHECK-NEXT: MemSize: +# CHECK-NEXT: Flags [ +# CHECK-NEXT: PF_R +# CHECK-NEXT: PF_X +# CHECK-NEXT: ] + +# FILL: 001000 90 cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc + +nop + +.section .foo,"ax" +.align 16 +nop +.zero 0x1000