macho_assembler/builder/
dylib_builder.rs

1use crate::types::{MachoHeader, MachoProgram, LoadCommand, CpuType, MachoType};
2use gaia_types::GaiaError;
3
4/// Mach-O 动态库构建器
5///
6/// 提供了构建 Mach-O 动态库文件的高级接口。
7#[derive(Debug)]
8pub struct DylibBuilder {
9    header: MachoHeader,
10    load_commands: Vec<LoadCommand>,
11}
12
13impl DylibBuilder {
14    /// 创建一个新的动态库构建器
15    pub fn new(cpu_type: CpuType) -> Self {
16        let header = MachoHeader {
17            magic: match cpu_type {
18                CpuType::X86_64 | CpuType::Arm64 => 0xfeedfacf, // MH_MAGIC_64
19                _ => 0xfeedface, // MH_MAGIC
20            },
21            cpu_type: cpu_type as u32,
22            cpu_subtype: 0,
23            file_type: MachoType::Dylib as u32,
24            ncmds: 0,
25            sizeofcmds: 0,
26            flags: 0,
27            reserved: match cpu_type {
28                CpuType::X86_64 | CpuType::Arm64 => Some(0),
29                _ => None,
30            },
31        };
32
33        Self {
34            header,
35            load_commands: Vec::new(),
36        }
37    }
38
39    /// 添加一个加载命令
40    pub fn add_load_command(mut self, cmd: u32, data: Vec<u8>) -> Self {
41        let cmdsize = 8 + data.len() as u32; // cmd + cmdsize + data
42        let load_cmd = LoadCommand {
43            cmd,
44            cmdsize,
45            data,
46        };
47        
48        self.load_commands.push(load_cmd);
49        self.header.ncmds += 1;
50        self.header.sizeofcmds += cmdsize;
51        
52        self
53    }
54
55    /// 设置文件标志
56    pub fn set_flags(mut self, flags: u32) -> Self {
57        self.header.flags = flags;
58        self
59    }
60
61    /// 构建 MachoProgram
62    pub fn build(self) -> Result<MachoProgram, GaiaError> {
63        Ok(MachoProgram {
64            header: self.header,
65            load_commands: self.load_commands,
66            segments: Vec::new(),
67            sections: Vec::new(),
68        })
69    }
70}
71
72impl Default for DylibBuilder {
73    fn default() -> Self {
74        Self::new(CpuType::X86_64)
75    }
76}