Craft Anything: understand how any software works, and craft your own.
Rust
Mach-O sections inherit read/write from their segment (#372)
GGWA41580837089b
diff --git a/crates/formats/src/binary.rs b/crates/formats/src/binary.rsindex e2f714bb..95b4b90a 100644--- a/crates/formats/src/binary.rs+++ b/crates/formats/src/binary.rs@@ -593,6 +593,17 @@ fn parse_object(data: &[u8], slice_offset: u64) -> Result<Binary, FormatError> {let name = seg.name().ok().flatten().map(String::from).unwrap_or_else(|| format!("LOAD{i}"));b.segments.push(Segment { name, addr: seg.address(), size: seg.size(), file_offset: o.saturating_add(slice_offset), file_size: n, read, write, exec });}+ if format == Format::MachO {+ for section in &mut b.sections {+ if let Some(segment) = b.segments.iter().find(|seg| {+ section.segment.as_deref() == Some(seg.name.as_str())+ && section.addr.checked_sub(seg.addr).and_then(|offset| offset.checked_add(section.size)).is_some_and(|end| end <= seg.size)+ }) {+ section.read = segment.read;+ section.write = segment.write;+ }+ }+ }// PE sections double as segments in `object`; keep one list.if format == Format::Pe {b.segments.clear();diff --git a/crates/formats/src/macho.rs b/crates/formats/src/macho.rsindex c0438f8e..bb19156a 100644--- a/crates/formats/src/macho.rs+++ b/crates/formats/src/macho.rs@@ -719,4 +719,28 @@ mod tests {let _ = crate::parse_binary(&d);}}++ #[test]+ fn read_only_segments_keep_stub_and_unwind_sections_read_only() {+ let mut m = tk::apple::macho_min(tk::apple::CPU_ARM64, 2, &[], &[("__text", &[0; 4]), ("__stubs", &[0; 12]), ("__unwind_info", &[0; 8])]);+ m[32 + 72 + 64..32 + 72 + 68].copy_from_slice(&0x8000_0400u32.to_le_bytes());+ m[32 + 72 + 80 + 64..32 + 72 + 80 + 68].copy_from_slice(&0x8000_0408u32.to_le_bytes());+ m.resize(0x4000, 0);+ let b = crate::parse_binary(&m).unwrap();+ assert_eq!(b.sections.len(), 3);+ assert!(!b.segments[0].write);+ for s in &b.sections {+ assert!(s.read);+ assert!(!s.write, "{} must inherit its read-only segment", s.name);+ }+ assert!(b.sections[0].exec);+ assert!(b.sections[1].exec);+ assert!(!b.sections[2].exec);+ m[32 + 56..32 + 60].copy_from_slice(&7u32.to_le_bytes());+ m[32 + 60..32 + 64].copy_from_slice(&3u32.to_le_bytes());+ let writable = crate::parse_binary(&m).unwrap();+ assert!(writable.sections.iter().all(|s| s.read && s.write));+ assert!(writable.sections[1].exec);+ assert!(!writable.sections[2].exec);+ }}