use crate::{
error::{Error, Result},
macho::{
LinkOptions, MachOFile, MachSection,
constants::{
ARM_THREAD_STATE64_COUNT, S_ATTR_PURE_INSTRUCTIONS,
S_ATTR_SOME_INSTRUCTIONS, S_NON_LAZY_SYMBOL_POINTERS,
S_SYMBOL_STUBS, S_THREAD_LOCAL_ZEROFILL, S_ZEROFILL, SECTION_TYPE,
VM_PROT_EXECUTE, VM_PROT_READ, X86_THREAD_STATE64_COUNT,
},
live::LiveSections,
reloc::MachoTarget,
symtab::CommonSym,
},
util::{align_up, pad_name, trim_nul},
};
pub const TEXT_BASE: u64 = 0x1_0000_0000;
pub const FILE_PAGE: u64 = 0x4000;
pub const HEADER_SIZE: u64 = 32;
const HEADER_PAD: u64 = 32;
#[derive(Clone, Copy)]
pub struct Member {
pub file: usize,
pub section: u32,
pub size: u64,
pub align: u32,
pub offset: u64,
}
pub struct OutSection {
pub segname: [u8; 16],
pub sectname: [u8; 16],
pub flags: u32,
pub align: u32,
pub members: Vec<Member>,
pub addr: u64,
pub offset: u64,
pub size: u64,
pub zerofill: bool,
pub reserved1: u32,
pub reserved2: u32,
}
pub struct OutSegment {
pub name: [u8; 16],
pub vmaddr: u64,
pub vmsize: u64,
pub fileoff: u64,
pub filesize: u64,
pub maxprot: u32,
pub initprot: u32,
pub sections: Vec<OutSection>,
}
#[derive(Clone, Copy)]
pub struct GotLayout {
pub addr: u64,
pub offset: u64,
pub count: u32,
}
#[derive(Clone, Copy)]
pub struct StubLayout {
pub addr: u64,
pub offset: u64,
pub count: u32,
}
pub struct MachLayout {
pub text: OutSegment,
pub data: Option<OutSegment>,
pub linkedit_vmaddr: u64,
pub linkedit_fileoff: u64,
pub linkedit_filesize: u64,
pub sizeofcmds: u32,
pub entry_off: u64,
pub sec_vaddr: Vec<Vec<u64>>,
pub got: Option<GotLayout>,
pub stubs: Option<StubLayout>,
pub common_addr: Vec<u64>,
}
pub fn build(
inputs: &[MachOFile<'_>],
linkedit_size: u64,
entry: &[u8],
got_count: u32,
commons: &[CommonSym<'_>],
target: MachoTarget,
options: &LinkOptions<'_>,
stub_count: u32,
unwind_entries: u32,
live: &LiveSections,
) -> Result<MachLayout> {
let mut text_secs = Vec::new();
let mut data_secs = Vec::new();
collect_sections(inputs, live, &mut text_secs, &mut data_secs);
if unwind_entries > 0 {
inject_unwind_info(&mut text_secs, unwind_entries);
}
if stub_count > 0 {
inject_stubs(&mut text_secs, stub_count);
}
if got_count > 0 {
inject_got_section(&mut data_secs, got_count, stub_count);
}
if !commons.is_empty() {
inject_common_section(&mut data_secs, commons);
}
let nsects_text = u32::try_from(text_secs.len())
.map_err(|_| Error::OutOfRange("text section count"))?;
let nsects_data = u32::try_from(data_secs.len())
.map_err(|_| Error::OutOfRange("data section count"))?;
let sizeofcmds = commands_size(nsects_text, nsects_data, target, options);
let text = place_text_segment(text_secs, sizeofcmds);
let data = place_data_segment(data_secs, &text);
let (linkedit_vmaddr, linkedit_fileoff) =
linkedit_extents(&text, data.as_ref());
let mut sec_vaddr = empty_section_map(inputs);
stamp(&text, &mut sec_vaddr);
if let Some(d) = data.as_ref() {
stamp(d, &mut sec_vaddr);
}
let entry_off = if options.dylib {
0
} else {
entry_offset(inputs, &sec_vaddr, entry)?
};
let got = find_got(data.as_ref());
let stubs = find_stubs(&text);
let common_addr = common_addresses(data.as_ref(), commons);
Ok(MachLayout {
text,
data,
linkedit_vmaddr,
linkedit_fileoff,
linkedit_filesize: linkedit_size,
sizeofcmds,
entry_off,
sec_vaddr,
got,
stubs,
common_addr,
})
}
fn inject_unwind_info(text_secs: &mut Vec<OutSection>, entries: u32) {
let size = crate::macho::unwind::section_size(entries);
let section = OutSection {
segname: pad_name(b"__TEXT"),
sectname: pad_name(b"__unwind_info"),
flags: 0,
align: 2,
members: Vec::new(),
addr: 0,
offset: 0,
size,
zerofill: false,
reserved1: 0,
reserved2: 0,
};
let at = text_secs
.iter()
.position(|candidate| trim_nul(&candidate.sectname) == b"__eh_frame")
.unwrap_or(text_secs.len());
text_secs.insert(at, section);
}
fn inject_got_section(
data_secs: &mut Vec<OutSection>,
got_count: u32,
stub_count: u32,
) {
let size = u64::from(got_count).checked_mul(8).unwrap_or(0);
data_secs.insert(
0,
OutSection {
segname: pad_name(b"__DATA"),
sectname: pad_name(b"__got"),
flags: S_NON_LAZY_SYMBOL_POINTERS,
align: 3,
members: Vec::new(),
addr: 0,
offset: 0,
size,
zerofill: false,
reserved1: stub_count,
reserved2: 0,
},
);
}
fn inject_stubs(text_secs: &mut Vec<OutSection>, stub_count: u32) {
text_secs.push(OutSection {
segname: pad_name(b"__TEXT"),
sectname: pad_name(b"__stubs"),
flags: S_SYMBOL_STUBS
| S_ATTR_PURE_INSTRUCTIONS
| S_ATTR_SOME_INSTRUCTIONS,
align: 2,
members: Vec::new(),
addr: 0,
offset: 0,
size: u64::from(stub_count).saturating_mul(12),
zerofill: false,
reserved1: 0,
reserved2: 12,
});
}
fn find_got(data: Option<&OutSegment>) -> Option<GotLayout> {
let seg = data?;
let got = seg
.sections
.iter()
.find(|s| trim_nul(&s.sectname) == b"__got")?;
let count = u32::try_from(got.size / 8).unwrap_or(0);
Some(GotLayout {
addr: got.addr,
offset: got.offset,
count,
})
}
fn find_stubs(text: &OutSegment) -> Option<StubLayout> {
let stubs = text
.sections
.iter()
.find(|s| trim_nul(&s.sectname) == b"__stubs")?;
Some(StubLayout {
addr: stubs.addr,
offset: stubs.offset,
count: u32::try_from(stubs.size / 12).unwrap_or(0),
})
}
fn inject_common_section(
data_secs: &mut Vec<OutSection>,
commons: &[CommonSym<'_>],
) {
let size = commons
.iter()
.try_fold(0u64, |cursor, c| {
let a = u64::from(1u32.checked_shl(c.align).unwrap_or(1));
align_up(cursor, a).checked_add(c.size)
})
.unwrap_or(0);
let align = commons.iter().map(|c| c.align).max().unwrap_or(0);
data_secs.push(OutSection {
segname: pad_name(b"__DATA"),
sectname: pad_name(b"__common"),
flags: S_ZEROFILL,
align,
members: Vec::new(),
addr: 0,
offset: 0,
size,
zerofill: true,
reserved1: 0,
reserved2: 0,
});
}
fn common_addresses(
data: Option<&OutSegment>,
commons: &[CommonSym<'_>],
) -> Vec<u64> {
let section = data
.and_then(|seg| {
seg.sections
.iter()
.find(|s| trim_nul(&s.sectname) == b"__common")
})
.filter(|_| !commons.is_empty());
let Some(section) = section else {
return Vec::new();
};
let mut cursor = section.addr;
commons
.iter()
.map(|c| {
let a = u64::from(1u32.checked_shl(c.align).unwrap_or(1));
cursor = align_up(cursor, a);
let at = cursor;
cursor = cursor.saturating_add(c.size);
at
})
.collect()
}
fn commands_size(
nsects_text: u32,
nsects_data: u32,
target: MachoTarget,
options: &LinkOptions<'_>,
) -> u32 {
let seg_text = 72 + 80 * nsects_text;
let seg_data = if nsects_data > 0 {
72 + 80 * nsects_data
} else {
0
};
let base = 72 + 24 + 80 + 24 + 72 * u32::from(!options.dylib);
let entry = if options.dylib {
48 + dylib_command_size(options.install_name.unwrap_or(""))
} else if options.dynamic {
48 + dylinker_command_size() + 24
} else {
thread_command_size(target)
};
let platform = 24 * u32::from(options.platform.is_some());
let dylibs = options.dylibs.iter().fold(0u32, |sum, name| {
sum.saturating_add(dylib_command_size(name.install_name))
});
let trailing = base + entry + platform + dylibs;
seg_text + seg_data + trailing
}
pub const fn dylinker_command_size() -> u32 {
align_command(12 + 14)
}
pub fn dylib_command_size(name: &str) -> u32 {
let name_len = u32::try_from(name.len()).unwrap_or(u32::MAX);
align_command(24u32.saturating_add(name_len).saturating_add(1))
}
const fn align_command(size: u32) -> u32 {
size.saturating_add(7) & !7
}
pub const fn thread_command_size(target: MachoTarget) -> u32 {
let words = match target {
MachoTarget::X86_64 => X86_THREAD_STATE64_COUNT,
MachoTarget::Arm64 => ARM_THREAD_STATE64_COUNT,
};
16 + 4 * words
}
fn place_text_segment(
mut sections: Vec<OutSection>,
sizeofcmds: u32,
) -> OutSegment {
order_sections(&mut sections);
let first_section = HEADER_SIZE + u64::from(sizeofcmds) + HEADER_PAD;
let mut cursor = first_section;
let mut vcursor = TEXT_BASE + first_section;
for s in &mut sections {
let a = u64::from(1u32.checked_shl(s.align).unwrap_or(1));
cursor = align_up(cursor, a);
vcursor = align_up(vcursor, a);
s.offset = cursor;
s.addr = vcursor;
cursor += s.size;
vcursor += s.size;
}
let filesize = align_up(cursor, FILE_PAGE);
OutSegment {
name: pad_name(b"__TEXT"),
vmaddr: TEXT_BASE,
vmsize: filesize,
fileoff: 0,
filesize,
maxprot: VM_PROT_READ | VM_PROT_EXECUTE,
initprot: VM_PROT_READ | VM_PROT_EXECUTE,
sections,
}
}
fn place_data_segment(
mut sections: Vec<OutSection>,
text: &OutSegment,
) -> Option<OutSegment> {
if sections.is_empty() {
return None;
}
order_sections(&mut sections);
let vmaddr = align_up(text.vmaddr + text.vmsize, FILE_PAGE);
let fileoff = align_up(text.fileoff + text.filesize, FILE_PAGE);
let mut cursor = fileoff;
let mut vcursor = vmaddr;
let mut last_file_end = fileoff;
let mut last_vm_end = vmaddr;
for s in &mut sections {
let a = u64::from(1u32.checked_shl(s.align).unwrap_or(1));
cursor = align_up(cursor, a);
vcursor = align_up(vcursor, a);
s.addr = vcursor;
if s.zerofill {
s.offset = 0;
} else {
s.offset = cursor;
cursor += s.size;
last_file_end = cursor;
}
vcursor = vcursor.wrapping_add(s.size);
last_vm_end = vcursor;
}
Some(OutSegment {
name: pad_name(b"__DATA"),
vmaddr,
vmsize: align_up(last_vm_end.wrapping_sub(vmaddr), FILE_PAGE),
fileoff,
filesize: align_up(last_file_end.wrapping_sub(fileoff), FILE_PAGE),
maxprot: VM_PROT_READ | crate::macho::constants::VM_PROT_WRITE,
initprot: VM_PROT_READ | crate::macho::constants::VM_PROT_WRITE,
sections,
})
}
fn linkedit_extents(
text: &OutSegment,
data: Option<&OutSegment>,
) -> (u64, u64) {
let (last_vmaddr, last_vmsize, last_fileoff, last_filesize) = data.map_or(
(text.vmaddr, text.vmsize, text.fileoff, text.filesize),
|d| (d.vmaddr, d.vmsize, d.fileoff, d.filesize),
);
let vmaddr = align_up(last_vmaddr + last_vmsize, FILE_PAGE);
let fileoff = align_up(last_fileoff + last_filesize, FILE_PAGE);
(vmaddr, fileoff)
}
fn order_sections(sections: &mut [OutSection]) {
sections.sort_by_key(|s| {
let name = trim_nul(&s.sectname);
if s.zerofill {
3
} else if name == b"__thread_vars" {
1
} else if name == b"__thread_data" {
2
} else {
0
}
});
}
fn stamp(segment: &OutSegment, sec_vaddr: &mut [Vec<u64>]) {
for s in &segment.sections {
for m in &s.members {
let zero_based =
usize::try_from(m.section).unwrap_or(0).saturating_sub(1);
let base = s.addr.wrapping_add(m.offset);
if let Some(file) = sec_vaddr.get_mut(m.file)
&& let Some(slot) = file.get_mut(zero_based)
{
*slot = base;
}
}
}
}
fn entry_offset(
inputs: &[MachOFile<'_>],
sec_vaddr: &[Vec<u64>],
entry: &[u8],
) -> Result<u64> {
for (file, input) in inputs.iter().enumerate() {
let syms = input.symbols();
for sym in &syms {
if sym.name != entry {
continue;
}
let zero_based = usize::from(sym.n_sect).saturating_sub(1);
let Some(base) =
sec_vaddr.get(file).and_then(|f| f.get(zero_based)).copied()
else {
continue;
};
let Some(frame) = input.section_addr(sym.n_sect) else {
continue;
};
let addr = base.wrapping_add(sym.n_value.wrapping_sub(frame));
return Ok(addr.wrapping_sub(TEXT_BASE));
}
}
Err(Error::UndefinedEntry(
String::from_utf8_lossy(entry).into_owned(),
))
}
fn collect_sections(
inputs: &[MachOFile<'_>],
live: &LiveSections,
text_secs: &mut Vec<OutSection>,
data_secs: &mut Vec<OutSection>,
) {
for (file, input) in inputs.iter().enumerate() {
for section in input.sections() {
if !is_linkable(§ion) || !live.section(file, section.index) {
continue;
}
if section.segname == b"__TEXT" {
add_member(text_secs, file, §ion);
} else {
add_member(data_secs, file, §ion);
}
}
}
layout_members(text_secs);
layout_members(data_secs);
}
fn add_member(
bucket: &mut Vec<OutSection>,
file: usize,
section: &MachSection<'_>,
) {
let key = (section.segname, section.sectname);
let out = bucket
.iter_mut()
.find(|s| (s.segname_for_cmp(), s.sectname_for_cmp()) == key);
let section_align = if section.sectname == b"__thread_vars" {
section.align.max(3)
} else {
section.align
};
let member = Member {
file,
section: section.index,
size: section.size,
align: section_align,
offset: 0,
};
if let Some(out) = out {
out.align = out.align.max(section_align);
out.members.push(member);
return;
}
bucket.push(OutSection {
segname: pad_name(section.segname),
sectname: pad_name(section.sectname),
flags: section.flags,
align: section_align,
members: vec![member],
addr: 0,
offset: 0,
size: 0,
zerofill: matches!(
section.flags & SECTION_TYPE,
S_ZEROFILL | S_THREAD_LOCAL_ZEROFILL
),
reserved1: 0,
reserved2: 0,
});
}
fn layout_members(sections: &mut [OutSection]) {
for s in sections {
let mut cursor = 0u64;
for m in &mut s.members {
let a = u64::from(1u32.checked_shl(m.align).unwrap_or(1));
cursor = align_up(cursor, a);
m.offset = cursor;
cursor += m.size;
}
s.size = cursor;
}
}
impl OutSection {
fn segname_for_cmp(&self) -> &[u8] {
trim_nul(&self.segname)
}
fn sectname_for_cmp(&self) -> &[u8] {
trim_nul(&self.sectname)
}
}
pub fn is_linkable(section: &MachSection<'_>) -> bool {
if !is_content_segment(section.segname) {
return false;
}
!is_deferred(section.sectname)
}
fn is_content_segment(segname: &[u8]) -> bool {
matches!(
segname,
b"__TEXT" | b"__DATA" | b"__DATA_CONST" | b"__DATA_DIRTY"
)
}
fn is_deferred(name: &[u8]) -> bool {
if name.starts_with(b"__debug") {
return true;
}
matches!(
name,
b"__unwind_info"
| b"__compact_unwind"
| b"__llvm_addrsig"
| b"__got"
| b"__la_symbol_ptr"
| b"__nl_symbol_ptr"
| b"__stubs"
| b"__stub_helper"
| b"__objc_imageinfo"
)
}
fn empty_section_map(inputs: &[MachOFile<'_>]) -> Vec<Vec<u64>> {
let mut out = Vec::with_capacity(inputs.len());
for input in inputs {
out.push(vec![0u64; input.sections().len()]);
}
out
}