Skip to content

Commit

Permalink
write/elf: Fix writing of aligned empty sections (gimli-rs#540)
Browse files Browse the repository at this point in the history
This was previously causing an assertion failure because the alignment
padding was not written to the buffer if the section was empty, which
caused subsequent sections to be placed at the wrong offsets.
  • Loading branch information
Amanieu authored May 9, 2023
1 parent 998c9a0 commit f918ed3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
9 changes: 3 additions & 6 deletions src/write/elf/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,12 +379,9 @@ impl<'a> Object<'a> {
}
}
for (index, section) in self.sections.iter().enumerate() {
let len = section.data.len();
if len != 0 {
writer.write_align(section.align as usize);
debug_assert_eq!(section_offsets[index].offset, writer.len());
writer.write(&section.data);
}
writer.write_align(section.align as usize);
debug_assert_eq!(section_offsets[index].offset, writer.len());
writer.write(&section.data);
}

// Write symbols.
Expand Down
23 changes: 23 additions & 0 deletions tests/aligned_sections.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#![cfg(feature = "write")]

use object::{
write::{Object, StreamingBuffer},
Architecture, BinaryFormat, Endianness, SectionKind,
};

#[test]
fn aligned_sections() {
let mut object = Object::new(BinaryFormat::Elf, Architecture::X86_64, Endianness::Little);

let text_section_id = object.add_section(vec![], b".text".to_vec(), SectionKind::Text);
let text_section = object.section_mut(text_section_id);
text_section.set_data(&[][..], 4096);

let data_section_id = object.add_section(vec![], b".data".to_vec(), SectionKind::Data);
let data_section = object.section_mut(data_section_id);
data_section.set_data(&b"1234"[..], 16);

let mut buffer = StreamingBuffer::new(vec![]);
object.emit(&mut buffer).unwrap();
buffer.result().unwrap();
}

0 comments on commit f918ed3

Please sign in to comment.