Skip to main content

linkerland_parser/
lib.rs

1use std::path::Path;
2use std::str;
3
4use serde::Serialize;
5
6use winnow::{
7    ascii::{digit1, line_ending, multispace0, till_line_ending},
8    combinator::{alt, delimited, eof, opt, peek, preceded, repeat, repeat_till, terminated},
9    error::{StrContext, StrContextValue},
10    token::literal,
11    Parser, Result as ParserResult,
12};
13
14#[derive(Debug, Serialize)]
15pub struct Symbol {
16    pub address: String,
17    pub size: String,
18    pub file_index: String,
19    pub name: String,
20}
21
22#[derive(Debug, Serialize)]
23pub struct Section {
24    pub address: String,
25    pub size: String,
26    pub segment: String,
27    pub section: String,
28}
29
30#[derive(Debug)]
31enum MapFileHeaders {
32    Path,
33    Architecture,
34    ObjectFiles,
35    Symbols,
36    Sections,
37}
38
39#[cfg(target_os = "macos")]
40impl MapFileHeaders {
41    fn as_str(&self) -> &str {
42        match self {
43            MapFileHeaders::Path => "# Path:",
44            MapFileHeaders::Architecture => "# Arch:",
45            MapFileHeaders::ObjectFiles => "# Object files:",
46            MapFileHeaders::Sections => "# Sections:",
47            MapFileHeaders::Symbols => "# Symbols:",
48        }
49    }
50}
51
52#[derive(Debug, Serialize, Clone, Copy, PartialEq, Eq)]
53pub enum BinaryFormat {
54    MachO,
55    Elf,
56    Unknown,
57}
58
59impl BinaryFormat {
60    pub fn as_str(&self) -> &'static str {
61        match self {
62            BinaryFormat::MachO => "Mach-O",
63            BinaryFormat::Elf => "ELF",
64            BinaryFormat::Unknown => "Unknown",
65        }
66    }
67}
68
69#[derive(Debug, Serialize)]
70pub struct ObjectFile {
71    pub index: i32,
72    pub path: String,
73}
74
75#[derive(Debug, Serialize)]
76pub struct MapFile {
77    pub arch: String,
78    pub object_files: Vec<ObjectFile>,
79    pub target_path: String,
80    pub symbols: Vec<Symbol>,
81    pub sections: Vec<Section>,
82    pub binary_format: BinaryFormat,
83}
84
85fn read_file(map_file: &Path) -> String {
86    match std::fs::read_to_string(map_file) {
87        Ok(contents) => contents,
88        Err(e) => {
89            panic!("Error reading file: {:?}", e);
90        }
91    }
92}
93
94/// Consume zero or more whitespace (spaces/tabs/newlines); helper (e.g. before `__TEXT`).
95fn spaces<'i>(input: &mut &'i str) -> ParserResult<&'i str> {
96    multispace0(input)
97}
98
99/// Parse architecture header (e.g. `# Arch: arm64` -> `arm64`).
100fn arch<'i>(input: &mut &'i str) -> ParserResult<&'i str> {
101    preceded(
102        preceded(
103            opt(line_ending),
104            preceded(literal(MapFileHeaders::Architecture.as_str()), multispace0),
105        ),
106        till_line_ending,
107    )
108    .parse_next(input)
109}
110
111/// Parse hex value starting `0x` (e.g. `0x1000007DC`).
112fn hex_value<'i>(input: &mut &'i str) -> ParserResult<&'i str> {
113    preceded("0x", winnow::ascii::hex_digit1)
114        .take()
115        .parse_next(input)
116}
117
118/// Parse one object file line (e.g. `[ 66] /path/libunwind.tbd`).
119fn object_file(input: &mut &str) -> ParserResult<ObjectFile> {
120    (
121        delimited('[', preceded(multispace0, digit1), ']'),
122        // Do NOT consume an optional preceding line_ending here; each object file line must start with '['
123        preceded(multispace0, till_line_ending),
124    )
125        .map(|(index, path): (&str, &str)| ObjectFile {
126            index: index.parse().unwrap(),
127            path: path.to_string(),
128        })
129        .parse_next(input)
130}
131
132/// Parse entire object files block after `# Object files:` until next header.
133fn object_files(input: &mut &str) -> ParserResult<Vec<ObjectFile>> {
134    delimited(
135        opt(line_ending),
136        literal(MapFileHeaders::ObjectFiles.as_str()),
137        line_ending,
138    )
139    .parse_next(input)?;
140
141    repeat(
142        0..,
143        terminated(preceded(peek('['), object_file), opt(line_ending)),
144    )
145    .parse_next(input)
146}
147
148/// Parse one symbol row (e.g. `0xADDR\t0xSIZE\t[  1] name`).
149fn symbol(input: &mut &str) -> ParserResult<Symbol> {
150    let address = preceded(multispace0, hex_value).parse_next(input);
151    let size = preceded(multispace0, hex_value).parse_next(input);
152    let file_index = preceded(
153        preceded(opt(line_ending), spaces),
154        delimited('[', preceded(multispace0, digit1), ']'),
155    )
156    .parse_next(input);
157    let name = preceded(spaces, till_line_ending).parse_next(input);
158    let symbol_addr = address.unwrap().to_string();
159    let symbol_size = size.unwrap().to_string();
160
161    let symbol = Symbol {
162        address: symbol_addr,
163        size: symbol_size,
164        file_index: file_index.unwrap().to_string(),
165        name: name.unwrap().to_string(),
166    };
167
168    Ok(symbol)
169}
170
171/// Parse consecutive symbol rows until header or EOF.
172fn symbols(input: &mut &str) -> ParserResult<Vec<Symbol>> {
173    repeat_till(
174        0..,
175        terminated(symbol, opt(line_ending)),
176        alt((literal("# "), eof)),
177    )
178    .parse_next(input)
179    .map(|(symbols, _)| symbols)
180}
181
182/// Parse full symbol table after `# Symbols:`.
183fn symbol_table(input: &mut &str) -> ParserResult<Vec<Symbol>> {
184    terminated(literal(MapFileHeaders::Symbols.as_str()), line_ending).parse_next(input)?;
185    terminated(till_line_ending, line_ending).parse_next(input)?;
186    symbols.parse_next(input)
187}
188
189/// Parse `__` identifier (segment/section) like `__TEXT` / `__text`.
190fn parse_segment_or_section<'a>(i: &mut &'a str) -> ParserResult<&'a str> {
191    let start = *i;
192    let _ = preceded(
193        "__",
194        winnow::token::take_while(1.., |c: char| c.is_ascii_alphanumeric() || c == '_'),
195    )
196    .parse_next(i)?;
197    let consumed_len = start.len() - i.len();
198    Ok(&start[..consumed_len])
199}
200
201/// Parse one section row (e.g. `0xADDR\t0xSIZE\t__SEG\t__sect`).
202fn section(input: &mut &str) -> ParserResult<Section> {
203    let address = preceded(multispace0, hex_value).parse_next(input);
204    let size = preceded(multispace0, hex_value).parse_next(input);
205    spaces.parse_next(input)?;
206    let segment_name = parse_segment_or_section.parse_next(input)?;
207    spaces.parse_next(input)?;
208    let section_name = parse_segment_or_section.parse_next(input)?;
209
210    Ok(Section {
211        address: address.unwrap().to_string(),
212        size: size.unwrap().to_string(),
213        segment: segment_name.to_string(),
214        section: section_name.to_string(),
215    })
216}
217
218/// Parse consecutive section rows until `# Symbols:` or EOF.
219fn sections(input: &mut &str) -> ParserResult<Vec<Section>> {
220    repeat_till(
221        0..,
222        terminated(section, opt(line_ending)),
223        alt((
224            peek(terminated(
225                preceded(spaces, literal(MapFileHeaders::Symbols.as_str())),
226                opt(line_ending),
227            )),
228            eof,
229        )),
230    )
231    .parse_next(input)
232    .map(|(sections, _)| sections)
233}
234
235/// Parse sections block after `# Sections:` header.
236fn section_table(input: &mut &str) -> ParserResult<Vec<Section>> {
237    delimited(
238        opt(line_ending),
239        literal(MapFileHeaders::Sections.as_str()),
240        line_ending,
241    )
242    .parse_next(input)?;
243    terminated(till_line_ending, line_ending).parse_next(input)?;
244    sections.parse_next(input)
245}
246
247/// Parse target path header (e.g. `# Path: /target/debug/deps/sample-app`).
248fn target_path<'i>(input: &mut &'i str) -> ParserResult<&'i str> {
249    preceded(
250        literal(MapFileHeaders::Path.as_str()),
251        preceded(multispace0, till_line_ending),
252    )
253    .context(StrContext::Label("Path"))
254    .context(StrContext::Expected(StrContextValue::Description(
255        "Expected a Path",
256    )))
257    .parse_next(input)
258}
259
260/// Detect binary format based on section names.
261fn detect_binary_format(sections: &[Section]) -> BinaryFormat {
262    // Check if any section starts with "__" (Mach-O style)
263    let has_macho_sections = sections
264        .iter()
265        .any(|s| s.segment.starts_with("__") || s.section.starts_with("__"));
266
267    // Check if any section starts with "." (ELF style)
268    let has_elf_sections = sections
269        .iter()
270        .any(|s| s.segment.starts_with('.') || s.section.starts_with('.'));
271
272    if has_macho_sections {
273        BinaryFormat::MachO
274    } else if has_elf_sections {
275        BinaryFormat::Elf
276    } else {
277        BinaryFormat::Unknown
278    }
279}
280
281/// Parse whole map: Path -> Arch -> Object files -> Sections -> Symbols.
282pub fn parse(map_file: &Path) -> ParserResult<MapFile> {
283    let contents = read_file(map_file);
284    let mut input = contents.as_str();
285
286    // Parse all fields first
287    let target_path = target_path(&mut input)?.to_string();
288    let arch = arch(&mut input)?.to_string();
289    let object_files = object_files(&mut input)?;
290    let sections = section_table(&mut input)?;
291    let symbols = symbol_table(&mut input)?;
292
293    // Detect binary format based on section names
294    let binary_format = detect_binary_format(&sections);
295
296    Ok(MapFile {
297        target_path,
298        arch,
299        object_files,
300        sections,
301        symbols,
302        binary_format,
303    })
304}
305
306#[cfg(test)]
307mod tests {
308
309    use super::*;
310
311    #[test]
312    fn test_arch() {
313        let mut input = "# Arch: x86_64";
314        let result = arch(&mut input);
315        assert_eq!(result.unwrap(), "x86_64");
316    }
317
318    #[test]
319    fn test_object_files() {
320        let mut input = r"# Object files:
321[ 66] /Library/Developer/CommandLineTools/SDKs/MacOSX14.4.sdk/usr/lib/system/libunwind.tbd";
322        let result = object_files(&mut input);
323        let object_files = result.unwrap();
324
325        assert_eq!(object_files.len(), 1);
326        assert_eq!(object_files[0].index, 66);
327        assert_eq!(
328            object_files[0].path,
329            "/Library/Developer/CommandLineTools/SDKs/MacOSX14.4.sdk/usr/lib/system/libunwind.tbd"
330        );
331    }
332
333    #[test]
334    fn test_target_path() {
335        let mut input = "# Path: /target/debug/deps/sample-app";
336        let result = target_path(&mut input);
337        assert_eq!(result.unwrap(), "/target/debug/deps/sample-app");
338    }
339
340    #[test]
341    fn test_object_files_immediately_followed_by_sections() {
342        let mut input = r"# Object files:
343[  0] a.o
344[  1] b.o
345# Sections:
346# Address	Size    	Segment Section
3470x0	0x1	__TEXT	__text";
348        let result = object_files(&mut input).unwrap();
349        assert_eq!(result.len(), 2);
350        assert_eq!(result[0].index, 0);
351        assert_eq!(result[0].path, "a.o");
352        // Remaining input should start with '# Sections:' now
353        assert!(input.starts_with("# Sections:"));
354    }
355
356    #[test]
357    fn test_symbol() {
358        let mut input = r"0x10004C058	0x00000018	[  1] __ZN3std3sys3pal4unix17thread_local_dtor13register_dtor5DTORS17hf7230a0b661819a4E";
359        let result = symbol(&mut input);
360        let symbol = result.unwrap();
361        assert_eq!(symbol.address, "0x10004C058");
362        assert_eq!(symbol.size, "0x00000018");
363        assert_eq!(symbol.file_index, "1");
364        assert_eq!(
365            symbol.name,
366            "__ZN3std3sys3pal4unix17thread_local_dtor13register_dtor5DTORS17hf7230a0b661819a4E"
367        );
368    }
369
370    #[test]
371    fn test_single_symbol_row() {
372        let mut input = r"0x10004C058	0x00000018	[  1] __ZN3std3sys3pal4unix17thread_local_dtor13register_dtor5DTORS17hf7230a0b661819a4E";
373        let result = symbols(&mut input);
374        let symbols = result.unwrap();
375        assert_eq!(symbols.len(), 1);
376        assert_eq!(symbols[0].address, "0x10004C058");
377    }
378
379    #[test]
380    fn test_multiple_symbol_rows() {
381        let mut input = r"
382        0x10004C058	0x00000018	[  1] __ZN3std3sys3pal4unix17thread_local_dtor13register_dtor5DTORS17hf7230a0b661819a4E
383        0x10004C059	0x00000020	[  2] __ZN3std3sys3pal4unix17thread_local_dtor13register_dtor5DTORS17hf7230a0b661819a4E";
384        let result = symbols(&mut input);
385        let symbols = result.unwrap();
386        assert_eq!(symbols.len(), 2);
387        assert_eq!(symbols[0].address, "0x10004C058");
388        assert_eq!(symbols[1].address, "0x10004C059");
389    }
390
391    #[test]
392    fn test_symbol_table() {
393        let mut input = r"# Symbols:
394    # Address	Size    	File  Name
395    0x10004C058	0x00000018	[  1] __ZN3std3sys3pal4unix17thread_local_dtor13register_dtor5DTORS17hf7230a0b661819a4E";
396        let result = symbol_table(&mut input);
397        let symbols = result.unwrap();
398        assert_eq!(symbols.len(), 1);
399        assert_eq!(symbols[0].address, "0x10004C058");
400    }
401
402    #[test]
403    fn test_single_section_row() {
404        let mut input = r"0x10004C058	0x00000018	__TEXT	__text";
405        let result = section(&mut input);
406        let section = result.unwrap();
407        assert_eq!(section.address, "0x10004C058");
408        assert_eq!(section.size, "0x00000018");
409        assert_eq!(section.segment, "__TEXT");
410        assert_eq!(section.section, "__text");
411    }
412
413    #[test]
414    fn test_section_with_underscores() {
415        // Use actual tab characters, matching fixture formatting
416        let mut input = "0x10003BBB8\t0x000017F4\t__TEXT\t__gcc_except_tab";
417        let result = section(&mut input).unwrap();
418        assert_eq!(result.segment, "__TEXT");
419        assert_eq!(result.section, "__gcc_except_tab");
420    }
421
422    #[test]
423    fn test_sections() {
424        let mut input = r"0x10004C058	0x00000018	__TEXT	__text
425        0x10004C059	0x00000020	__TEXT	__text";
426        let result = sections(&mut input);
427        let sections = result.unwrap();
428        assert_eq!(sections.len(), 2);
429        assert_eq!(sections[0].address, "0x10004C058");
430        assert_eq!(sections[0].section, "__text");
431        assert_eq!(sections[0].segment, "__TEXT");
432        assert_eq!(sections[1].address, "0x10004C059");
433        assert_eq!(sections[1].section, "__text");
434        assert_eq!(sections[1].segment, "__TEXT");
435    }
436
437    #[test]
438    fn test_binary_format_detection_macho() {
439        let sections = vec![
440            Section {
441                address: "0x1000007DC".to_string(),
442                size: "0x00036FC4".to_string(),
443                segment: "__TEXT".to_string(),
444                section: "__text".to_string(),
445            },
446            Section {
447                address: "0x100048000".to_string(),
448                size: "0x00000208".to_string(),
449                segment: "__DATA".to_string(),
450                section: "__data".to_string(),
451            },
452        ];
453        assert_eq!(detect_binary_format(&sections), BinaryFormat::MachO);
454    }
455
456    #[test]
457    fn test_binary_format_detection_elf() {
458        let sections = vec![
459            Section {
460                address: "0x1000".to_string(),
461                size: "0x1234".to_string(),
462                segment: ".text".to_string(),
463                section: ".text".to_string(),
464            },
465            Section {
466                address: "0x2000".to_string(),
467                size: "0x5678".to_string(),
468                segment: ".data".to_string(),
469                section: ".data".to_string(),
470            },
471        ];
472        assert_eq!(detect_binary_format(&sections), BinaryFormat::Elf);
473    }
474
475    #[test]
476    fn test_section_table() {
477        let mut input = r"# Sections:
478        # Address	Size    	Segment Section
479        0x10004C058	0x00000018	__TEXT	__text";
480        let result = section_table(&mut input);
481        let sections = result.unwrap();
482        assert_eq!(sections.len(), 1);
483        assert_eq!(sections[0].address, "0x10004C058");
484        assert_eq!(sections[0].size, "0x00000018");
485        assert_eq!(sections[0].segment, "__TEXT");
486        assert_eq!(sections[0].section, "__text");
487    }
488
489    #[test]
490    fn test_section_table_stops_at_symbols() {
491        let mut input = r"# Sections:
492    # Address	Size    	Segment Section
493    0x10004C058	0x00000018	__TEXT	__text
494    # Symbols:
495    0x10004C060	0x00000030	[  1] some_symbol";
496        let result = section_table(&mut input);
497        let sections = result.unwrap();
498        assert_eq!(sections.len(), 1);
499        assert_eq!(sections[0].address, "0x10004C058");
500    }
501
502    #[test]
503    fn test_parse_small_sample() {
504        let map_file = Path::new("tests/fixtures/sample.map");
505        let result = parse(map_file).unwrap();
506        assert_eq!(result.target_path, "/target/debug/deps/sample-app");
507        assert_eq!(result.arch, "arm64");
508        assert_eq!(result.object_files.len(), 1);
509        assert_eq!(result.sections.len(), 1);
510        assert_eq!(result.symbols.len(), 1);
511    }
512
513    #[test]
514    fn test_parse_large_sample() {
515        let map_file = Path::new("tests/fixtures/linker.map");
516        let result = parse(map_file).unwrap();
517        assert_eq!(
518            result.target_path,
519            "/target/debug/deps/learning_linkers-97732971bdfee10d"
520        );
521        assert_eq!(result.arch, "arm64");
522        assert_eq!(result.object_files.len(), 67);
523        assert_eq!(result.sections.len(), 14);
524        assert!(!result.symbols.is_empty());
525    }
526}