objdiff_core/diff/
mod.rs

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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
use std::collections::HashSet;

use anyhow::Result;

use crate::{
    diff::{
        code::{diff_code, no_diff_code, process_code_symbol},
        data::{
            diff_bss_section, diff_bss_symbol, diff_data_section, diff_data_symbol,
            diff_generic_section, no_diff_symbol,
        },
    },
    obj::{ObjInfo, ObjIns, ObjSection, ObjSectionKind, ObjSymbol, SymbolRef},
};

pub mod code;
pub mod data;
pub mod display;

#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    serde::Deserialize,
    serde::Serialize,
    strum::VariantArray,
    strum::EnumMessage,
    tsify_next::Tsify,
)]
pub enum X86Formatter {
    #[default]
    #[strum(message = "Intel (default)")]
    Intel,
    #[strum(message = "AT&T")]
    Gas,
    #[strum(message = "NASM")]
    Nasm,
    #[strum(message = "MASM")]
    Masm,
}

#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    serde::Deserialize,
    serde::Serialize,
    strum::VariantArray,
    strum::EnumMessage,
    tsify_next::Tsify,
)]
pub enum MipsAbi {
    #[default]
    #[strum(message = "Auto (default)")]
    Auto,
    #[strum(message = "O32")]
    O32,
    #[strum(message = "N32")]
    N32,
    #[strum(message = "N64")]
    N64,
}

#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    serde::Deserialize,
    serde::Serialize,
    strum::VariantArray,
    strum::EnumMessage,
    tsify_next::Tsify,
)]
pub enum MipsInstrCategory {
    #[default]
    #[strum(message = "Auto (default)")]
    Auto,
    #[strum(message = "CPU")]
    Cpu,
    #[strum(message = "RSP (N64)")]
    Rsp,
    #[strum(message = "R3000 GTE (PS1)")]
    R3000Gte,
    #[strum(message = "R4000 ALLEGREX (PSP)")]
    R4000Allegrex,
    #[strum(message = "R5900 EE (PS2)")]
    R5900,
}

#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    serde::Deserialize,
    serde::Serialize,
    strum::VariantArray,
    strum::EnumMessage,
    tsify_next::Tsify,
)]
pub enum ArmArchVersion {
    #[default]
    #[strum(message = "Auto (default)")]
    Auto,
    #[strum(message = "ARMv4T (GBA)")]
    V4T,
    #[strum(message = "ARMv5TE (DS)")]
    V5TE,
    #[strum(message = "ARMv6K (3DS)")]
    V6K,
}

#[derive(
    Debug,
    Copy,
    Clone,
    Default,
    Eq,
    PartialEq,
    serde::Deserialize,
    serde::Serialize,
    strum::VariantArray,
    strum::EnumMessage,
    tsify_next::Tsify,
)]
pub enum ArmR9Usage {
    #[default]
    #[strum(
        message = "R9 or V6 (default)",
        detailed_message = "Use R9 as a general-purpose register."
    )]
    GeneralPurpose,
    #[strum(
        message = "SB (static base)",
        detailed_message = "Used for position-independent data (PID)."
    )]
    Sb,
    #[strum(message = "TR (TLS register)", detailed_message = "Used for thread-local storage.")]
    Tr,
}

#[inline]
const fn default_true() -> bool { true }

#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, tsify_next::Tsify)]
#[tsify(from_wasm_abi)]
#[serde(default)]
pub struct DiffObjConfig {
    pub relax_reloc_diffs: bool,
    #[serde(default = "default_true")]
    pub space_between_args: bool,
    pub combine_data_sections: bool,
    // x86
    pub x86_formatter: X86Formatter,
    // MIPS
    pub mips_abi: MipsAbi,
    pub mips_instr_category: MipsInstrCategory,
    // ARM
    pub arm_arch_version: ArmArchVersion,
    pub arm_unified_syntax: bool,
    pub arm_av_registers: bool,
    pub arm_r9_usage: ArmR9Usage,
    pub arm_sl_usage: bool,
    pub arm_fp_usage: bool,
    pub arm_ip_usage: bool,
}

impl Default for DiffObjConfig {
    fn default() -> Self {
        Self {
            relax_reloc_diffs: false,
            space_between_args: true,
            combine_data_sections: false,
            x86_formatter: Default::default(),
            mips_abi: Default::default(),
            mips_instr_category: Default::default(),
            arm_arch_version: Default::default(),
            arm_unified_syntax: true,
            arm_av_registers: false,
            arm_r9_usage: Default::default(),
            arm_sl_usage: false,
            arm_fp_usage: false,
            arm_ip_usage: false,
        }
    }
}

impl DiffObjConfig {
    pub fn separator(&self) -> &'static str {
        if self.space_between_args {
            ", "
        } else {
            ","
        }
    }
}

#[derive(Debug, Clone)]
pub struct ObjSectionDiff {
    pub symbols: Vec<ObjSymbolDiff>,
    pub data_diff: Vec<ObjDataDiff>,
    pub match_percent: Option<f32>,
}

impl ObjSectionDiff {
    fn merge(&mut self, other: ObjSectionDiff) {
        // symbols ignored
        self.data_diff = other.data_diff;
        self.match_percent = other.match_percent;
    }
}

#[derive(Debug, Clone, Default)]
pub struct ObjSymbolDiff {
    pub symbol_ref: SymbolRef,
    pub diff_symbol: Option<SymbolRef>,
    pub instructions: Vec<ObjInsDiff>,
    pub match_percent: Option<f32>,
}

#[derive(Debug, Clone, Default)]
pub struct ObjInsDiff {
    pub ins: Option<ObjIns>,
    /// Diff kind
    pub kind: ObjInsDiffKind,
    /// Branches from instruction
    pub branch_from: Option<ObjInsBranchFrom>,
    /// Branches to instruction
    pub branch_to: Option<ObjInsBranchTo>,
    /// Arg diffs
    pub arg_diff: Vec<Option<ObjInsArgDiff>>,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum ObjInsDiffKind {
    #[default]
    None,
    OpMismatch,
    ArgMismatch,
    Replace,
    Delete,
    Insert,
}

#[derive(Debug, Clone, Default)]
pub struct ObjDataDiff {
    pub data: Vec<u8>,
    pub kind: ObjDataDiffKind,
    pub len: usize,
    pub symbol: String,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum ObjDataDiffKind {
    #[default]
    None,
    Replace,
    Delete,
    Insert,
}

#[derive(Debug, Copy, Clone)]
pub struct ObjInsArgDiff {
    /// Incrementing index for coloring
    pub idx: usize,
}

#[derive(Debug, Clone)]
pub struct ObjInsBranchFrom {
    /// Source instruction indices
    pub ins_idx: Vec<usize>,
    /// Incrementing index for coloring
    pub branch_idx: usize,
}

#[derive(Debug, Clone)]
pub struct ObjInsBranchTo {
    /// Target instruction index
    pub ins_idx: usize,
    /// Incrementing index for coloring
    pub branch_idx: usize,
}

#[derive(Default)]
pub struct ObjDiff {
    pub sections: Vec<ObjSectionDiff>,
    pub common: Vec<ObjSymbolDiff>,
}

impl ObjDiff {
    pub fn new_from_obj(obj: &ObjInfo) -> Self {
        let mut result = Self {
            sections: Vec::with_capacity(obj.sections.len()),
            common: Vec::with_capacity(obj.common.len()),
        };
        for (section_idx, section) in obj.sections.iter().enumerate() {
            let mut symbols = Vec::with_capacity(section.symbols.len());
            for (symbol_idx, _) in section.symbols.iter().enumerate() {
                symbols.push(ObjSymbolDiff {
                    symbol_ref: SymbolRef { section_idx, symbol_idx },
                    diff_symbol: None,
                    instructions: vec![],
                    match_percent: None,
                });
            }
            result.sections.push(ObjSectionDiff {
                symbols,
                data_diff: vec![ObjDataDiff {
                    data: section.data.clone(),
                    kind: ObjDataDiffKind::None,
                    len: section.data.len(),
                    symbol: section.name.clone(),
                }],
                match_percent: None,
            });
        }
        for (symbol_idx, _) in obj.common.iter().enumerate() {
            result.common.push(ObjSymbolDiff {
                symbol_ref: SymbolRef { section_idx: obj.sections.len(), symbol_idx },
                diff_symbol: None,
                instructions: vec![],
                match_percent: None,
            });
        }
        result
    }

    #[inline]
    pub fn section_diff(&self, section_idx: usize) -> &ObjSectionDiff {
        &self.sections[section_idx]
    }

    #[inline]
    pub fn section_diff_mut(&mut self, section_idx: usize) -> &mut ObjSectionDiff {
        &mut self.sections[section_idx]
    }

    #[inline]
    pub fn symbol_diff(&self, symbol_ref: SymbolRef) -> &ObjSymbolDiff {
        if symbol_ref.section_idx == self.sections.len() {
            &self.common[symbol_ref.symbol_idx]
        } else {
            &self.section_diff(symbol_ref.section_idx).symbols[symbol_ref.symbol_idx]
        }
    }

    #[inline]
    pub fn symbol_diff_mut(&mut self, symbol_ref: SymbolRef) -> &mut ObjSymbolDiff {
        if symbol_ref.section_idx == self.sections.len() {
            &mut self.common[symbol_ref.symbol_idx]
        } else {
            &mut self.section_diff_mut(symbol_ref.section_idx).symbols[symbol_ref.symbol_idx]
        }
    }
}

#[derive(Default)]
pub struct DiffObjsResult {
    pub left: Option<ObjDiff>,
    pub right: Option<ObjDiff>,
    pub prev: Option<ObjDiff>,
}

pub fn diff_objs(
    config: &DiffObjConfig,
    left: Option<&ObjInfo>,
    right: Option<&ObjInfo>,
    prev: Option<&ObjInfo>,
) -> Result<DiffObjsResult> {
    let symbol_matches = matching_symbols(left, right, prev)?;
    let section_matches = matching_sections(left, right)?;
    let mut left = left.map(|p| (p, ObjDiff::new_from_obj(p)));
    let mut right = right.map(|p| (p, ObjDiff::new_from_obj(p)));
    let mut prev = prev.map(|p| (p, ObjDiff::new_from_obj(p)));

    for symbol_match in symbol_matches {
        match symbol_match {
            SymbolMatch {
                left: Some(left_symbol_ref),
                right: Some(right_symbol_ref),
                prev: prev_symbol_ref,
                section_kind,
            } => {
                let (left_obj, left_out) = left.as_mut().unwrap();
                let (right_obj, right_out) = right.as_mut().unwrap();
                match section_kind {
                    ObjSectionKind::Code => {
                        let left_code = process_code_symbol(left_obj, left_symbol_ref, config)?;
                        let right_code = process_code_symbol(right_obj, right_symbol_ref, config)?;
                        let (left_diff, right_diff) = diff_code(
                            &left_code,
                            &right_code,
                            left_symbol_ref,
                            right_symbol_ref,
                            config,
                        )?;
                        *left_out.symbol_diff_mut(left_symbol_ref) = left_diff;
                        *right_out.symbol_diff_mut(right_symbol_ref) = right_diff;

                        if let Some(prev_symbol_ref) = prev_symbol_ref {
                            let (prev_obj, prev_out) = prev.as_mut().unwrap();
                            let prev_code = process_code_symbol(prev_obj, prev_symbol_ref, config)?;
                            let (_, prev_diff) = diff_code(
                                &right_code,
                                &prev_code,
                                right_symbol_ref,
                                prev_symbol_ref,
                                config,
                            )?;
                            *prev_out.symbol_diff_mut(prev_symbol_ref) = prev_diff;
                        }
                    }
                    ObjSectionKind::Data => {
                        let (left_diff, right_diff) = diff_data_symbol(
                            left_obj,
                            right_obj,
                            left_symbol_ref,
                            right_symbol_ref,
                        )?;
                        *left_out.symbol_diff_mut(left_symbol_ref) = left_diff;
                        *right_out.symbol_diff_mut(right_symbol_ref) = right_diff;
                    }
                    ObjSectionKind::Bss => {
                        let (left_diff, right_diff) = diff_bss_symbol(
                            left_obj,
                            right_obj,
                            left_symbol_ref,
                            right_symbol_ref,
                        )?;
                        *left_out.symbol_diff_mut(left_symbol_ref) = left_diff;
                        *right_out.symbol_diff_mut(right_symbol_ref) = right_diff;
                    }
                }
            }
            SymbolMatch { left: Some(left_symbol_ref), right: None, prev: _, section_kind } => {
                let (left_obj, left_out) = left.as_mut().unwrap();
                match section_kind {
                    ObjSectionKind::Code => {
                        let code = process_code_symbol(left_obj, left_symbol_ref, config)?;
                        *left_out.symbol_diff_mut(left_symbol_ref) =
                            no_diff_code(&code, left_symbol_ref)?;
                    }
                    ObjSectionKind::Data | ObjSectionKind::Bss => {
                        *left_out.symbol_diff_mut(left_symbol_ref) =
                            no_diff_symbol(left_obj, left_symbol_ref);
                    }
                }
            }
            SymbolMatch { left: None, right: Some(right_symbol_ref), prev: _, section_kind } => {
                let (right_obj, right_out) = right.as_mut().unwrap();
                match section_kind {
                    ObjSectionKind::Code => {
                        let code = process_code_symbol(right_obj, right_symbol_ref, config)?;
                        *right_out.symbol_diff_mut(right_symbol_ref) =
                            no_diff_code(&code, right_symbol_ref)?;
                    }
                    ObjSectionKind::Data | ObjSectionKind::Bss => {
                        *right_out.symbol_diff_mut(right_symbol_ref) =
                            no_diff_symbol(right_obj, right_symbol_ref);
                    }
                }
            }
            SymbolMatch { left: None, right: None, .. } => {
                // Should not happen
            }
        }
    }

    for section_match in section_matches {
        if let SectionMatch {
            left: Some(left_section_idx),
            right: Some(right_section_idx),
            section_kind,
        } = section_match
        {
            let (left_obj, left_out) = left.as_mut().unwrap();
            let (right_obj, right_out) = right.as_mut().unwrap();
            let left_section = &left_obj.sections[left_section_idx];
            let right_section = &right_obj.sections[right_section_idx];
            match section_kind {
                ObjSectionKind::Code => {
                    let left_section_diff = left_out.section_diff(left_section_idx);
                    let right_section_diff = right_out.section_diff(right_section_idx);
                    let (left_diff, right_diff) = diff_generic_section(
                        left_section,
                        right_section,
                        left_section_diff,
                        right_section_diff,
                    )?;
                    left_out.section_diff_mut(left_section_idx).merge(left_diff);
                    right_out.section_diff_mut(right_section_idx).merge(right_diff);
                }
                ObjSectionKind::Data => {
                    let left_section_diff = left_out.section_diff(left_section_idx);
                    let right_section_diff = right_out.section_diff(right_section_idx);
                    let (left_diff, right_diff) = diff_data_section(
                        left_section,
                        right_section,
                        left_section_diff,
                        right_section_diff,
                    )?;
                    left_out.section_diff_mut(left_section_idx).merge(left_diff);
                    right_out.section_diff_mut(right_section_idx).merge(right_diff);
                }
                ObjSectionKind::Bss => {
                    let left_section_diff = left_out.section_diff(left_section_idx);
                    let right_section_diff = right_out.section_diff(right_section_idx);
                    let (left_diff, right_diff) = diff_bss_section(
                        left_section,
                        right_section,
                        left_section_diff,
                        right_section_diff,
                    )?;
                    left_out.section_diff_mut(left_section_idx).merge(left_diff);
                    right_out.section_diff_mut(right_section_idx).merge(right_diff);
                }
            }
        }
    }

    Ok(DiffObjsResult {
        left: left.map(|(_, o)| o),
        right: right.map(|(_, o)| o),
        prev: prev.map(|(_, o)| o),
    })
}

#[derive(Copy, Clone, Eq, PartialEq)]
struct SymbolMatch {
    left: Option<SymbolRef>,
    right: Option<SymbolRef>,
    prev: Option<SymbolRef>,
    section_kind: ObjSectionKind,
}

#[derive(Copy, Clone, Eq, PartialEq)]
struct SectionMatch {
    left: Option<usize>,
    right: Option<usize>,
    section_kind: ObjSectionKind,
}

/// Find matching symbols between each object.
fn matching_symbols(
    left: Option<&ObjInfo>,
    right: Option<&ObjInfo>,
    prev: Option<&ObjInfo>,
) -> Result<Vec<SymbolMatch>> {
    let mut matches = Vec::new();
    let mut right_used = HashSet::new();
    if let Some(left) = left {
        for (section_idx, section) in left.sections.iter().enumerate() {
            for (symbol_idx, symbol) in section.symbols.iter().enumerate() {
                let symbol_match = SymbolMatch {
                    left: Some(SymbolRef { section_idx, symbol_idx }),
                    right: find_symbol(right, symbol, section, Some(&right_used)),
                    prev: find_symbol(prev, symbol, section, None),
                    section_kind: section.kind,
                };
                matches.push(symbol_match);
                if let Some(right) = symbol_match.right {
                    right_used.insert(right);
                }
            }
        }
        for (symbol_idx, symbol) in left.common.iter().enumerate() {
            let symbol_match = SymbolMatch {
                left: Some(SymbolRef { section_idx: left.sections.len(), symbol_idx }),
                right: find_common_symbol(right, symbol),
                prev: find_common_symbol(prev, symbol),
                section_kind: ObjSectionKind::Bss,
            };
            matches.push(symbol_match);
            if let Some(right) = symbol_match.right {
                right_used.insert(right);
            }
        }
    }
    if let Some(right) = right {
        for (section_idx, section) in right.sections.iter().enumerate() {
            for (symbol_idx, symbol) in section.symbols.iter().enumerate() {
                let symbol_ref = SymbolRef { section_idx, symbol_idx };
                if right_used.contains(&symbol_ref) {
                    continue;
                }
                matches.push(SymbolMatch {
                    left: None,
                    right: Some(symbol_ref),
                    prev: find_symbol(prev, symbol, section, None),
                    section_kind: section.kind,
                });
            }
        }
        for (symbol_idx, symbol) in right.common.iter().enumerate() {
            let symbol_ref = SymbolRef { section_idx: right.sections.len(), symbol_idx };
            if right_used.contains(&symbol_ref) {
                continue;
            }
            matches.push(SymbolMatch {
                left: None,
                right: Some(symbol_ref),
                prev: find_common_symbol(prev, symbol),
                section_kind: ObjSectionKind::Bss,
            });
        }
    }
    Ok(matches)
}

fn unmatched_symbols<'section, 'used>(
    section: &'section ObjSection,
    section_idx: usize,
    used: Option<&'used HashSet<SymbolRef>>,
) -> impl Iterator<Item = (usize, &'section ObjSymbol)> + 'used
where
    'section: 'used,
{
    section.symbols.iter().enumerate().filter(move |&(symbol_idx, _)| {
        // Skip symbols that have already been matched
        !used.map(|u| u.contains(&SymbolRef { section_idx, symbol_idx })).unwrap_or(false)
    })
}

fn find_symbol(
    obj: Option<&ObjInfo>,
    in_symbol: &ObjSymbol,
    in_section: &ObjSection,
    used: Option<&HashSet<SymbolRef>>,
) -> Option<SymbolRef> {
    let obj = obj?;
    // Try to find an exact name match
    for (section_idx, section) in obj.sections.iter().enumerate() {
        if section.kind != in_section.kind {
            continue;
        }
        if let Some((symbol_idx, _)) = unmatched_symbols(section, section_idx, used)
            .find(|(_, symbol)| symbol.name == in_symbol.name)
        {
            return Some(SymbolRef { section_idx, symbol_idx });
        }
    }
    // Match compiler-generated symbols against each other (e.g. @251 -> @60)
    // If they are at the same address in the same section
    if in_symbol.name.starts_with('@')
        && matches!(in_section.kind, ObjSectionKind::Data | ObjSectionKind::Bss)
    {
        if let Some((section_idx, section)) =
            obj.sections.iter().enumerate().find(|(_, s)| s.name == in_section.name)
        {
            if let Some((symbol_idx, _)) =
                unmatched_symbols(section, section_idx, used).find(|(_, symbol)| {
                    symbol.address == in_symbol.address && symbol.name.starts_with('@')
                })
            {
                return Some(SymbolRef { section_idx, symbol_idx });
            }
        }
    }
    // Match Metrowerks symbol$1234 against symbol$2345
    if let Some((prefix, suffix)) = in_symbol.name.split_once('$') {
        if !suffix.chars().all(char::is_numeric) {
            return None;
        }
        for (section_idx, section) in obj.sections.iter().enumerate() {
            if section.kind != in_section.kind {
                continue;
            }
            if let Some((symbol_idx, _)) =
                unmatched_symbols(section, section_idx, used).find(|&(_, symbol)| {
                    if let Some((p, s)) = symbol.name.split_once('$') {
                        prefix == p && s.chars().all(char::is_numeric)
                    } else {
                        false
                    }
                })
            {
                return Some(SymbolRef { section_idx, symbol_idx });
            }
        }
    }
    None
}

fn find_common_symbol(obj: Option<&ObjInfo>, in_symbol: &ObjSymbol) -> Option<SymbolRef> {
    let obj = obj?;
    for (symbol_idx, symbol) in obj.common.iter().enumerate() {
        if symbol.name == in_symbol.name {
            return Some(SymbolRef { section_idx: obj.sections.len(), symbol_idx });
        }
    }
    None
}

/// Find matching sections between each object.
fn matching_sections(left: Option<&ObjInfo>, right: Option<&ObjInfo>) -> Result<Vec<SectionMatch>> {
    let mut matches = Vec::new();
    if let Some(left) = left {
        for (section_idx, section) in left.sections.iter().enumerate() {
            matches.push(SectionMatch {
                left: Some(section_idx),
                right: find_section(right, &section.name, section.kind),
                section_kind: section.kind,
            });
        }
    }
    if let Some(right) = right {
        for (section_idx, section) in right.sections.iter().enumerate() {
            if matches.iter().any(|m| m.right == Some(section_idx)) {
                continue;
            }
            matches.push(SectionMatch {
                left: None,
                right: Some(section_idx),
                section_kind: section.kind,
            });
        }
    }
    Ok(matches)
}

fn find_section(obj: Option<&ObjInfo>, name: &str, section_kind: ObjSectionKind) -> Option<usize> {
    for (section_idx, section) in obj?.sections.iter().enumerate() {
        if section.kind != section_kind {
            continue;
        }
        if section.name == name {
            return Some(section_idx);
        }
    }
    None
}