| 1 |
use object::read::macho::MachHeader; |
| 2 |
use object::read::{Object, ObjectSection}; |
| 3 |
use object::{macho, read, write, Architecture, BinaryFormat, Endianness}; |
| 4 |
|
| 5 |
// Test that segment size is valid when the first section needs alignment. |
| 6 |
#[test] |
| 7 |
fn issue_286_segment_file_size() { |
| 8 |
let mut object = write::Object::new( |
| 9 |
BinaryFormat::MachO, |
| 10 |
Architecture::X86_64, |
| 11 |
Endianness::Little, |
| 12 |
); |
| 13 |
|
| 14 |
let text = object.section_id(write::StandardSection::Text); |
| 15 |
object.append_section_data(text, &[1; 30], 0x1000); |
| 16 |
|
| 17 |
let bytes = &*object.write().unwrap(); |
| 18 |
let header = macho::MachHeader64::parse(bytes, 0).unwrap(); |
| 19 |
let endian: Endianness = header.endian().unwrap(); |
| 20 |
let mut commands = header.load_commands(endian, bytes, 0).unwrap(); |
| 21 |
let command = commands.next().unwrap().unwrap(); |
| 22 |
let (segment, _) = command.segment_64().unwrap().unwrap(); |
| 23 |
assert_eq!(segment.vmsize.get(endian), 30); |
| 24 |
assert_eq!(segment.filesize.get(endian), 30); |
| 25 |
} |
| 26 |
|
| 27 |
// We were emitting section file alignment padding that didn't match the address alignment padding. |
| 28 |
#[test] |
| 29 |
fn issue_552_section_file_alignment() { |
| 30 |
let mut object = write::Object::new( |
| 31 |
BinaryFormat::MachO, |
| 32 |
Architecture::X86_64, |
| 33 |
Endianness::Little, |
| 34 |
); |
| 35 |
|
| 36 |
// The starting file offset is not a multiple of 32 (checked later). |
| 37 |
// Length of 32 ensures that the file offset of the end of this section is still not a |
| 38 |
// multiple of 32. |
| 39 |
let section = object.add_section(vec![], vec![], object::SectionKind::ReadOnlyDataWithRel); |
| 40 |
object.append_section_data(section, &[0u8; 32], 1); |
| 41 |
|
| 42 |
// Address is already aligned correctly, so there must not any padding, |
| 43 |
// even though file offset is not aligned. |
| 44 |
let section = object.add_section(vec![], vec![], object::SectionKind::ReadOnlyData); |
| 45 |
object.append_section_data(section, &[0u8; 1], 32); |
| 46 |
|
| 47 |
let bytes = &*object.write().unwrap(); |
| 48 |
//std::fs::write(&"align.o", &bytes).unwrap(); |
| 49 |
let object = read::File::parse(bytes).unwrap(); |
| 50 |
let mut sections = object.sections(); |
| 51 |
|
| 52 |
let section = sections.next().unwrap(); |
| 53 |
let offset = section.file_range().unwrap().0; |
| 54 |
// Check file offset is not aligned to 32. |
| 55 |
assert_ne!(offset % 32, 0); |
| 56 |
assert_eq!(section.address(), 0); |
| 57 |
assert_eq!(section.size(), 32); |
| 58 |
|
| 59 |
let section = sections.next().unwrap(); |
| 60 |
// Check there is no padding. |
| 61 |
assert_eq!(section.file_range(), Some((offset + 32, 1))); |
| 62 |
assert_eq!(section.address(), 32); |
| 63 |
assert_eq!(section.size(), 1); |
| 64 |
} |