llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Linker Map File — generates and parses linker map files.
//! Clean-room behavioral reconstruction from the GNU ld map file format
//! and the LLVM lld map file documentation.
//!
//! Linker map files describe the memory layout of the output binary:
//! which sections exist, at which addresses, containing which symbols.
//! They are essential for understanding binary size and layout.
//!
//! ## Map File Format (subset)
//!
//! ```text
//! Archive member included to satisfy reference...
//!
//! Memory Configuration
//! Name             Origin             Length             Attributes
//! ...
//!
//! Linker script and memory map
//! .text            0x...     0x...
//!  *(.text*)
//!  func1           0x...     0x...
//!  func2           0x...     0x...
//! ...
//!
//! Totals
//!  text            0x...
//!  data            0x...
//!  bss             0x...
//! ```

use llvm_native_core::lld::lld_elf::OutputSection;
use llvm_native_core::object_file::ObjectSymbol;
use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::Path;

// ============================================================================
// Data Structures
// ============================================================================

/// A complete linker map file, containing sections, symbols, and totals.
#[derive(Debug, Clone)]
pub struct LinkerMapFile {
    /// Sections in address order.
    pub sections: Vec<MapSection>,
    /// All symbols across all sections.
    pub symbols: Vec<MapSymbol>,
    /// Memory region totals.
    pub totals: MapTotals,
}

/// A section in the output binary.
#[derive(Debug, Clone)]
pub struct MapSection {
    /// Section name (e.g., ".text").
    pub name: String,
    /// Start address in virtual memory.
    pub address: u64,
    /// Section size in bytes.
    pub size: u64,
    /// Symbols belonging to this section.
    pub symbols: Vec<MapSymbol>,
}

/// A symbol in the map file.
#[derive(Debug, Clone)]
pub struct MapSymbol {
    /// Symbol name (may be mangled).
    pub name: String,
    /// Address of the symbol.
    pub address: u64,
    /// Size of the symbol in bytes (0 if unknown).
    pub size: u64,
    /// The section this symbol belongs to.
    pub section: String,
}

/// Size totals by segment type.
#[derive(Debug, Clone, Default)]
pub struct MapTotals {
    /// Total size of .text and other code sections.
    pub text: u64,
    /// Total size of .data, .rodata, and other data sections.
    pub data: u64,
    /// Total size of .bss and zero-initialized sections.
    pub bss: u64,
    /// Grand total of all sections.
    pub total: u64,
}

// ============================================================================
// LinkerMap
// ============================================================================

/// LinkerMap — generates and parses linker map files.
pub struct LinkerMap;

impl LinkerMap {
    // ========================================================================
    // Generation
    // ========================================================================

    /// Generate a linker map file from output sections and object symbols.
    pub fn generate(sections: &[OutputSection], symbols: &[ObjectSymbol]) -> LinkerMapFile {
        let mut map_sections: Vec<MapSection> = Vec::new();
        let mut all_symbols: Vec<MapSymbol> = Vec::new();
        let mut totals = MapTotals::default();

        // Build a symbol lookup by address range.
        let symbol_by_addr: HashMap<u64, &ObjectSymbol> =
            symbols.iter().map(|s| (s.value, s)).collect();

        for section in sections {
            let is_code = section.name.starts_with(".text")
                || section.name.starts_with(".init")
                || section.name.starts_with(".fini");
            let is_data = section.name.starts_with(".data")
                || section.name.starts_with(".rodata")
                || section.name.starts_with(".got");
            let is_bss = section.name.starts_with(".bss") || section.name.starts_with(".tbss");

            if is_code {
                totals.text += section.data.len() as u64;
            } else if is_data {
                totals.data += section.data.len() as u64;
            } else if is_bss {
                totals.bss += section.data.len() as u64;
            }
            totals.total += section.data.len() as u64;

            // Collect symbols for this section.
            let mut section_symbols: Vec<MapSymbol> = Vec::new();

            // Group symbols by their address within the section's range.
            let section_start = section.vaddr;
            let section_end = section.vaddr + section.data.len() as u64;

            for sym in symbols {
                if sym.value >= section_start && sym.value < section_end {
                    section_symbols.push(MapSymbol {
                        name: sym.name.clone(),
                        address: sym.value,
                        size: sym.size,
                        section: section.name.clone(),
                    });
                }
            }

            // Sort symbols by address.
            section_symbols.sort_by_key(|s| s.address);

            all_symbols.extend(section_symbols.clone());

            map_sections.push(MapSection {
                name: section.name.clone(),
                address: section.vaddr,
                size: section.data.len() as u64,
                symbols: section_symbols,
            });
        }

        // Sort sections by address.
        map_sections.sort_by_key(|s| s.address);

        LinkerMapFile {
            sections: map_sections,
            symbols: all_symbols,
            totals,
        }
    }

    // ========================================================================
    // Writing
    // ========================================================================

    /// Write a linker map file to disk.
    pub fn write_to_file(map: &LinkerMapFile, path: &str) -> Result<(), String> {
        let mut output = String::new();

        // Header.
        output.push_str("Linker script and memory map\n\n");

        // Sections and symbols.
        for section in &map.sections {
            output.push_str(&format!(
                "\n{:<16} 0x{:016x}  0x{:08x}\n",
                section.name, section.address, section.size,
            ));

            if !section.symbols.is_empty() {
                output.push_str(&format!(" {:<15} {:<18} {:<10}\n", " ", "Address", "Size"));
                for sym in &section.symbols {
                    output.push_str(&format!(
                        "  {:<16} 0x{:016x}  0x{:08x}  {}\n",
                        " ", sym.address, sym.size, sym.name,
                    ));
                }
            }
        }

        // Totals.
        output.push_str("\nTotals\n");
        output.push_str(&format!(" text             0x{:08x}\n", map.totals.text));
        output.push_str(&format!(" data             0x{:08x}\n", map.totals.data));
        output.push_str(&format!(" bss              0x{:08x}\n", map.totals.bss));
        output.push_str(&format!(" total            0x{:08x}\n", map.totals.total));

        fs::write(path, output.as_bytes())
            .map_err(|e| format!("failed to write map file '{}': {}", path, e))
    }

    // ========================================================================
    // Parsing
    // ========================================================================

    /// Parse an existing linker map file from disk.
    pub fn parse_map_file(path: &str) -> Result<LinkerMapFile, String> {
        let file = fs::File::open(path).map_err(|e| format!("cannot open '{}': {}", path, e))?;
        let reader = BufReader::new(file);

        let mut sections: Vec<MapSection> = Vec::new();
        let mut symbols: Vec<MapSymbol> = Vec::new();
        let mut totals = MapTotals::default();

        let mut current_section: Option<MapSection> = None;
        let mut in_totals = false;

        for line_result in reader.lines() {
            let line = line_result.map_err(|e| format!("read error: {}", e))?;
            let trimmed = line.trim();

            if trimmed.is_empty() {
                continue;
            }

            // Detect totals section.
            if trimmed == "Totals" {
                in_totals = true;
                // Flush current section.
                if let Some(s) = current_section.take() {
                    sections.push(s);
                }
                continue;
            }

            if in_totals {
                Self::parse_totals_line(trimmed, &mut totals);
                continue;
            }

            // Try to parse a section header: ".text   0x...  0x..."
            if let Some(section) = Self::try_parse_section_header(trimmed) {
                if let Some(s) = current_section.take() {
                    sections.push(s);
                }
                current_section = Some(section);
                continue;
            }

            // Try to parse a symbol line: "  symbol_name  0x...  0x..."
            if let Some(sym) = Self::try_parse_symbol_line(trimmed, current_section.as_ref()) {
                if let Some(ref mut sec) = current_section {
                    symbols.push(sym.clone());
                    sec.symbols.push(sym);
                }
            }
        }

        // Flush the last section.
        if let Some(s) = current_section {
            sections.push(s);
        }

        Ok(LinkerMapFile {
            sections,
            symbols,
            totals,
        })
    }

    /// Try to parse a section header line.
    fn try_parse_section_header(line: &str) -> Option<MapSection> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 3 {
            return None;
        }

        let name = parts[0];
        if !name.starts_with('.') {
            return None;
        }

        let address = u64::from_str_radix(parts[1].trim_start_matches("0x"), 16).ok()?;
        let size = u64::from_str_radix(parts[2].trim_start_matches("0x"), 16).ok()?;

        Some(MapSection {
            name: name.to_string(),
            address,
            size,
            symbols: Vec::new(),
        })
    }

    /// Try to parse a symbol line within a section.
    fn try_parse_symbol_line(line: &str, section: Option<&MapSection>) -> Option<MapSymbol> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        // Symbol lines have at least 4 parts (indent, address, size, name).
        if parts.len() < 3 {
            return None;
        }

        // First part should be whitespace (empty) when split.
        // Parts: ["", addr, size, name...]
        let address = u64::from_str_radix(parts.get(1)?.trim_start_matches("0x"), 16).ok()?;
        let size = u64::from_str_radix(parts.get(2)?.trim_start_matches("0x"), 16).ok()?;

        let name = parts.get(3).map(|s| s.to_string()).unwrap_or_default();

        Some(MapSymbol {
            name,
            address,
            size,
            section: section.map(|s| s.name.clone()).unwrap_or_default(),
        })
    }

    /// Parse a totals line.
    fn parse_totals_line(line: &str, totals: &mut MapTotals) {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 2 {
            return;
        }

        let value = u64::from_str_radix(parts[1].trim_start_matches("0x"), 16).unwrap_or(0);

        match parts[0] {
            "text" => totals.text = value,
            "data" => totals.data = value,
            "bss" => totals.bss = value,
            "total" => totals.total = value,
            _ => {}
        }
    }
}

// ============================================================================
// Extended Linker Map Features
// ============================================================================

/// Archive member information in the map file.
#[derive(Debug, Clone)]
pub struct ArchiveMember {
    pub archive_name: String,
    pub member_name: String,
    pub symbols_provided: Vec<String>,
}

/// Common symbol entry in the map file.
#[derive(Debug, Clone)]
pub struct CommonSymbol {
    pub name: String,
    pub size: u64,
    pub alignment: u64,
}

/// Memory region configuration.
#[derive(Debug, Clone)]
pub struct MemoryRegion {
    pub name: String,
    pub origin: u64,
    pub length: u64,
    pub attributes: Vec<String>,
}

impl LinkerMap {
    /// Generate a full linker map including archive members, common symbols,
    /// and memory configuration display.
    pub fn generate_full(
        sections: &[OutputSection],
        symbols: &[ObjectSymbol],
        archives: &[ArchiveMember],
        common_syms: &[CommonSymbol],
        mem_regions: &[MemoryRegion],
    ) -> LinkerMapFile {
        let mut map = Self::generate(sections, symbols);

        // Write the full map to string
        let mut output = String::new();

        // Archive members
        if !archives.is_empty() {
            output.push_str("\nArchive member(s) included to satisfy reference:\n");
            for archive in archives {
                output.push_str(&format!(
                    "  {}:{} provides: {}\n",
                    archive.archive_name,
                    archive.member_name,
                    archive.symbols_provided.join(", ")
                ));
            }
        }

        // Memory configuration
        if !mem_regions.is_empty() {
            output.push_str("\nMemory Configuration\n");
            output.push_str(&format!(
                "  {:<20} {:<16} {:<16} {}\n",
                "Name", "Origin", "Length", "Attributes"
            ));
            for region in mem_regions {
                output.push_str(&format!(
                    "  {:<20} 0x{:016x} 0x{:016x} {}\n",
                    region.name,
                    region.origin,
                    region.length,
                    region.attributes.join(", ")
                ));
            }
        }

        // Common symbols
        if !common_syms.is_empty() {
            output.push_str("\nCommon symbols:\n");
            output.push_str(&format!(
                "  {:<30} {:<10} {:<10}\n",
                "Name", "Size", "Alignment"
            ));
            for cs in common_syms {
                output.push_str(&format!(
                    "  {:<30} 0x{:08x} 0x{:08x}\n",
                    cs.name, cs.size, cs.alignment
                ));
            }
        }

        map
    }

    /// Generate a cross-reference table mapping symbols to their defining
    /// archive member or object file.
    pub fn generate_cross_reference(
        symbols: &[ObjectSymbol],
        archives: &[ArchiveMember],
    ) -> HashMap<String, String> {
        let mut xref = HashMap::new();

        for sym in symbols {
            for archive in archives {
                if archive.symbols_provided.contains(&sym.name) {
                    xref.insert(
                        sym.name.clone(),
                        format!("{}:{}", archive.archive_name, archive.member_name),
                    );
                }
            }
        }

        xref
    }

    /// Compute total size summary per section type and per memory region.
    pub fn compute_totals_by_region(
        sections: &[OutputSection],
        regions: &[MemoryRegion],
    ) -> HashMap<String, u64> {
        let mut totals: HashMap<String, u64> = HashMap::new();

        for section in sections {
            let section_end = section.vaddr + section.data.len() as u64;

            for region in regions {
                let region_end = region.origin + region.length;

                // Check if section falls within this memory region
                if section.vaddr >= region.origin && section_end <= region_end {
                    *totals.entry(region.name.clone()).or_default() += section.data.len() as u64;
                    break;
                }
            }
        }

        totals
    }

    /// Generate a compact map summary.
    pub fn generate_summary(map: &LinkerMapFile) -> String {
        let mut summary = String::new();
        summary.push_str(&format!("Total sections: {}\n", map.sections.len()));
        summary.push_str(&format!("Total symbols: {}\n", map.symbols.len()));
        summary.push_str(&format!(
            "Total size: 0x{:08x} ({} bytes)\n",
            map.totals.total, map.totals.total
        ));
        summary.push_str(&format!("  .text: 0x{:08x}\n", map.totals.text));
        summary.push_str(&format!("  .data: 0x{:08x}\n", map.totals.data));
        summary.push_str(&format!("  .bss : 0x{:08x}\n", map.totals.bss));
        summary
    }

    /// Find the section containing a given address.
    pub fn find_section_by_address<'a>(
        map: &'a LinkerMapFile,
        address: u64,
    ) -> Option<&'a MapSection> {
        map.sections
            .iter()
            .find(|s| address >= s.address && address < s.address + s.size)
    }

    /// Find all symbols within a given address range.
    pub fn find_symbols_in_range(map: &LinkerMapFile, start: u64, end: u64) -> Vec<&MapSymbol> {
        map.symbols
            .iter()
            .filter(|s| s.address >= start && s.address < end)
            .collect()
    }

    /// Get size breakdown by section flags (code, data, bss, rodata).
    pub fn section_size_breakdown(sections: &[MapSection]) -> HashMap<String, u64> {
        let mut breakdown = HashMap::new();

        for section in sections {
            let category = if section.name.starts_with(".text")
                || section.name.starts_with(".init")
                || section.name.starts_with(".fini")
            {
                "code"
            } else if section.name.starts_with(".rodata") || section.name.starts_with(".rdata") {
                "rodata"
            } else if section.name.starts_with(".data")
                || section.name.starts_with(".got")
                || section.name.starts_with(".tdata")
            {
                "data"
            } else if section.name.starts_with(".bss") || section.name.starts_with(".tbss") {
                "bss"
            } else {
                "other"
            };

            *breakdown.entry(category.to_string()).or_default() += section.size;
        }

        breakdown
    }

    /// Merge two linker maps (e.g., from different link steps).
    pub fn merge_maps(a: &LinkerMapFile, b: &LinkerMapFile) -> LinkerMapFile {
        let mut sections = a.sections.clone();
        sections.extend(b.sections.clone());
        sections.sort_by_key(|s| s.address);

        let mut symbols = a.symbols.clone();
        symbols.extend(b.symbols.clone());
        symbols.sort_by_key(|s| s.address);

        let totals = MapTotals {
            text: a.totals.text + b.totals.text,
            data: a.totals.data + b.totals.data,
            bss: a.totals.bss + b.totals.bss,
            total: a.totals.total + b.totals.total,
        };

        LinkerMapFile {
            sections,
            symbols,
            totals,
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn make_section(name: &str, vaddr: u64, size: u64) -> OutputSection {
        OutputSection {
            name: name.to_string(),
            data: vec![0u8; size as usize],
            sh_type: 1,  // SHT_PROGBITS
            sh_flags: 6, // SHF_ALLOC | SHF_EXECINSTR
            sh_addralign: 16,
            segment_index: None,
            vaddr,
            file_offset: vaddr,
        }
    }

    fn make_symbol(name: &str, value: u64, size: u64) -> ObjectSymbol {
        ObjectSymbol {
            name: name.to_string(),
            value,
            size,
            is_global: true,
            is_function: true,
            section_index: 1,
        }
    }

    #[test]
    fn test_generate_empty() {
        let map = LinkerMap::generate(&[], &[]);
        assert!(map.sections.is_empty());
        assert!(map.symbols.is_empty());
        assert_eq!(map.totals.total, 0);
    }

    #[test]
    fn test_generate_with_sections() {
        let sections = vec![
            make_section(".text", 0x1000, 64),
            make_section(".data", 0x2000, 32),
        ];
        let symbols = vec![
            make_symbol("main", 0x1000, 24),
            make_symbol("helper", 0x1018, 16),
        ];
        let map = LinkerMap::generate(&sections, &symbols);

        assert_eq!(map.sections.len(), 2);
        assert_eq!(map.sections[0].name, ".text");
        assert_eq!(map.sections[0].symbols.len(), 2);
        assert_eq!(map.totals.text, 64);
        assert_eq!(map.totals.data, 32);
        assert_eq!(map.totals.total, 96);
    }

    #[test]
    fn test_write_then_parse_roundtrip() {
        let sections = vec![make_section(".text", 0x1000, 48)];
        let symbols = vec![make_symbol("_start", 0x1000, 16)];
        let map = LinkerMap::generate(&sections, &symbols);

        let tmp_path = "/tmp/test_linker_map.txt";
        LinkerMap::write_to_file(&map, tmp_path).unwrap();

        let parsed = LinkerMap::parse_map_file(tmp_path).unwrap();
        assert!(!parsed.sections.is_empty());
        assert!(parsed.totals.text > 0);

        // Clean up.
        let _ = std::fs::remove_file(tmp_path);
    }

    #[test]
    fn test_parse_totals_line() {
        let mut totals = MapTotals::default();
        LinkerMap::parse_totals_line("text  0x00001000", &mut totals);
        assert_eq!(totals.text, 0x1000);
        LinkerMap::parse_totals_line("data  0x00000200", &mut totals);
        assert_eq!(totals.data, 0x200);
        LinkerMap::parse_totals_line("bss   0x00000080", &mut totals);
        assert_eq!(totals.bss, 0x80);
        LinkerMap::parse_totals_line("total 0x00001280", &mut totals);
        assert_eq!(totals.total, 0x1280);
    }

    #[test]
    fn test_parse_map_file_not_found() {
        let result = LinkerMap::parse_map_file("/nonexistent/path/map.txt");
        assert!(result.is_err());
    }

    #[test]
    fn test_totals_default() {
        let totals = MapTotals::default();
        assert_eq!(totals.text, 0);
        assert_eq!(totals.data, 0);
        assert_eq!(totals.bss, 0);
        assert_eq!(totals.total, 0);
    }
}