forked from encounter/objdiff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
816 lines (767 loc) · 28.9 KB
/
mod.rs
File metadata and controls
816 lines (767 loc) · 28.9 KB
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use alloc::{
collections::{BTreeMap, BTreeSet},
string::String,
vec,
vec::Vec,
};
use core::{num::NonZeroU32, ops::Range};
use anyhow::Result;
use crate::{
diff::{
code::{diff_code, no_diff_code},
data::{
diff_bss_section, diff_bss_symbol, diff_data_section, diff_data_symbol,
diff_generic_section, no_diff_bss_section, no_diff_data_section, no_diff_data_symbol,
symbol_name_matches,
},
},
obj::{InstructionRef, Object, Relocation, SectionKind, Symbol, SymbolFlag},
};
pub mod code;
pub mod data;
pub mod demangler;
pub mod display;
include!(concat!(env!("OUT_DIR"), "/config.gen.rs"));
impl DiffObjConfig {
pub fn separator(&self) -> &'static str { if self.space_between_args { ", " } else { "," } }
}
#[derive(Debug, Clone)]
pub struct SectionDiff {
// pub target_section: Option<usize>,
pub match_percent: Option<f32>,
pub data_diff: Vec<DataDiff>,
pub reloc_diff: Vec<DataRelocationDiff>,
}
#[derive(Debug, Clone, Default)]
pub struct SymbolDiff {
/// The symbol index in the _other_ object that this symbol was diffed against
pub target_symbol: Option<usize>,
pub match_percent: Option<f32>,
pub diff_score: Option<(u64, u64)>,
pub instruction_rows: Vec<InstructionDiffRow>,
pub data_rows: Vec<DataDiffRow>,
}
#[derive(Debug, Clone, Default)]
pub struct MappingSymbolDiff {
pub symbol_index: usize,
pub symbol_diff: SymbolDiff,
}
#[derive(Debug, Clone, Default)]
pub struct InstructionDiffRow {
/// Instruction reference
pub ins_ref: Option<InstructionRef>,
/// Diff kind
pub kind: InstructionDiffKind,
/// Branches from instruction(s)
pub branch_from: Option<InstructionBranchFrom>,
/// Branches to instruction
pub branch_to: Option<InstructionBranchTo>,
/// Arg diffs
pub arg_diff: Vec<InstructionArgDiffIndex>,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum InstructionDiffKind {
#[default]
None,
OpMismatch,
ArgMismatch,
Replace,
Delete,
Insert,
}
#[derive(Debug, Clone, Default)]
pub struct DataDiff {
pub data: Vec<u8>,
pub size: usize,
pub kind: DataDiffKind,
}
#[derive(Debug, Clone)]
pub struct DataRelocationDiff {
pub reloc: Relocation,
pub range: Range<u64>,
pub kind: DataDiffKind,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
pub enum DataDiffKind {
#[default]
None,
Replace,
Delete,
Insert,
}
#[derive(Debug, Clone, Default)]
pub struct DataDiffRow {
pub address: u64,
pub segments: Vec<DataDiff>,
pub relocations: Vec<DataRelocationDiff>,
}
/// Index of the argument diff for coloring.
#[repr(transparent)]
#[derive(Debug, Copy, Clone, Default)]
pub struct InstructionArgDiffIndex(pub Option<NonZeroU32>);
impl InstructionArgDiffIndex {
pub const NONE: Self = Self(None);
#[inline(always)]
pub fn new(idx: u32) -> Self {
Self(Some(unsafe { NonZeroU32::new_unchecked(idx.saturating_add(1)) }))
}
#[inline(always)]
pub fn get(&self) -> Option<u32> { self.0.map(|idx| idx.get() - 1) }
#[inline(always)]
pub fn is_some(&self) -> bool { self.0.is_some() }
#[inline(always)]
pub fn is_none(&self) -> bool { self.0.is_none() }
}
#[derive(Debug, Clone)]
pub struct InstructionBranchFrom {
/// Source instruction indices
pub ins_idx: Vec<u32>,
/// Incrementing index for coloring
pub branch_idx: u32,
}
#[derive(Debug, Clone)]
pub struct InstructionBranchTo {
/// Target instruction index
pub ins_idx: u32,
/// Incrementing index for coloring
pub branch_idx: u32,
}
#[derive(Debug, Default)]
pub struct ObjectDiff {
/// A list of all symbol diffs in the object.
pub symbols: Vec<SymbolDiff>,
/// A list of all section diffs in the object.
pub sections: Vec<SectionDiff>,
/// If `selecting_left` or `selecting_right` is set, this is the list of symbols
/// that are being mapped to the other object.
pub mapping_symbols: Vec<MappingSymbolDiff>,
}
impl ObjectDiff {
pub fn new_from_obj(obj: &Object) -> Self {
let mut result = Self {
symbols: Vec::with_capacity(obj.symbols.len()),
sections: Vec::with_capacity(obj.sections.len()),
mapping_symbols: vec![],
};
for _ in obj.symbols.iter() {
result.symbols.push(SymbolDiff {
target_symbol: None,
match_percent: None,
diff_score: None,
..Default::default()
});
}
for _ in obj.sections.iter() {
result.sections.push(SectionDiff {
// target_section: None,
match_percent: None,
data_diff: vec![],
reloc_diff: vec![],
});
}
result
}
}
#[derive(Debug, Default)]
pub struct DiffObjsResult {
pub left: Option<ObjectDiff>,
pub right: Option<ObjectDiff>,
pub prev: Option<ObjectDiff>,
}
pub fn diff_objs(
left: Option<&Object>,
right: Option<&Object>,
prev: Option<&Object>,
diff_config: &DiffObjConfig,
mapping_config: &MappingConfig,
) -> Result<DiffObjsResult> {
let symbol_matches = matching_symbols(left, right, prev, mapping_config)?;
let section_matches = matching_sections(left, right)?;
let mut left = left.map(|p| (p, ObjectDiff::new_from_obj(p)));
let mut right = right.map(|p| (p, ObjectDiff::new_from_obj(p)));
let mut prev = prev.map(|p| (p, ObjectDiff::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 {
SectionKind::Code => {
let (left_diff, right_diff) = diff_code(
left_obj,
right_obj,
left_symbol_ref,
right_symbol_ref,
diff_config,
)?;
left_out.symbols[left_symbol_ref] = left_diff;
right_out.symbols[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_diff) = diff_code(
left_obj,
right_obj,
right_symbol_ref,
prev_symbol_ref,
diff_config,
)?;
prev_out.symbols[prev_symbol_ref] = prev_diff;
}
}
SectionKind::Data => {
let (left_diff, right_diff) = diff_data_symbol(
left_obj,
right_obj,
left_symbol_ref,
right_symbol_ref,
)?;
left_out.symbols[left_symbol_ref] = left_diff;
right_out.symbols[right_symbol_ref] = right_diff;
}
SectionKind::Bss | SectionKind::Common => {
let (left_diff, right_diff) = diff_bss_symbol(
left_obj,
right_obj,
left_symbol_ref,
right_symbol_ref,
)?;
left_out.symbols[left_symbol_ref] = left_diff;
right_out.symbols[right_symbol_ref] = right_diff;
}
SectionKind::Unknown => unreachable!(),
}
}
SymbolMatch { left: Some(left_symbol_ref), right: None, prev: _, section_kind } => {
let (left_obj, left_out) = left.as_mut().unwrap();
match section_kind {
SectionKind::Code => {
left_out.symbols[left_symbol_ref] =
no_diff_code(left_obj, left_symbol_ref, diff_config)?;
}
SectionKind::Data => {
left_out.symbols[left_symbol_ref] =
no_diff_data_symbol(left_obj, left_symbol_ref)?;
}
SectionKind::Bss | SectionKind::Common => {
// Nothing needs to be done
}
SectionKind::Unknown => unreachable!(),
}
}
SymbolMatch { left: None, right: Some(right_symbol_ref), prev: _, section_kind } => {
let (right_obj, right_out) = right.as_mut().unwrap();
match section_kind {
SectionKind::Code => {
right_out.symbols[right_symbol_ref] =
no_diff_code(right_obj, right_symbol_ref, diff_config)?;
}
SectionKind::Data => {
right_out.symbols[right_symbol_ref] =
no_diff_data_symbol(right_obj, right_symbol_ref)?;
}
SectionKind::Bss | SectionKind::Common => {
// Nothing needs to be done
}
SectionKind::Unknown => unreachable!(),
}
}
SymbolMatch { left: None, right: None, .. } => {
// Should not happen
}
}
}
for section_match in section_matches {
match section_match {
SectionMatch {
left: Some(left_section_idx),
right: Some(right_section_idx),
section_kind,
} => {
let (left_obj, left_out) = left.as_mut().unwrap();
let (right_obj, right_out) = right.as_mut().unwrap();
match section_kind {
SectionKind::Code => {
let (left_diff, right_diff) = diff_generic_section(
left_obj,
right_obj,
left_out,
right_out,
left_section_idx,
right_section_idx,
)?;
left_out.sections[left_section_idx] = left_diff;
right_out.sections[right_section_idx] = right_diff;
}
SectionKind::Data => {
let (left_diff, right_diff) = diff_data_section(
left_obj,
right_obj,
left_out,
right_out,
left_section_idx,
right_section_idx,
)?;
left_out.sections[left_section_idx] = left_diff;
right_out.sections[right_section_idx] = right_diff;
}
SectionKind::Bss | SectionKind::Common => {
let (left_diff, right_diff) = diff_bss_section(
left_obj,
right_obj,
left_out,
right_out,
left_section_idx,
right_section_idx,
)?;
left_out.sections[left_section_idx] = left_diff;
right_out.sections[right_section_idx] = right_diff;
}
SectionKind::Unknown => unreachable!(),
}
}
SectionMatch { left: Some(left_section_idx), right: None, section_kind } => {
let (left_obj, left_out) = left.as_mut().unwrap();
match section_kind {
SectionKind::Code => {}
SectionKind::Data => {
left_out.sections[left_section_idx] =
no_diff_data_section(left_obj, left_section_idx)?;
}
SectionKind::Bss | SectionKind::Common => {
left_out.sections[left_section_idx] = no_diff_bss_section()?;
}
SectionKind::Unknown => unreachable!(),
}
}
SectionMatch { left: None, right: Some(right_section_idx), section_kind } => {
let (right_obj, right_out) = right.as_mut().unwrap();
match section_kind {
SectionKind::Code => {}
SectionKind::Data => {
right_out.sections[right_section_idx] =
no_diff_data_section(right_obj, right_section_idx)?;
}
SectionKind::Bss | SectionKind::Common => {
right_out.sections[right_section_idx] = no_diff_bss_section()?;
}
SectionKind::Unknown => unreachable!(),
}
}
SectionMatch { left: None, right: None, .. } => {
// Should not happen
}
}
}
if let (Some((right_obj, right_out)), Some((left_obj, left_out))) =
(right.as_mut(), left.as_mut())
{
if let Some(right_name) = mapping_config.selecting_left.as_deref() {
generate_mapping_symbols(
left_obj,
left_out,
right_obj,
right_out,
MappingSymbol::Right(right_name),
diff_config,
)?;
}
if let Some(left_name) = mapping_config.selecting_right.as_deref() {
generate_mapping_symbols(
left_obj,
left_out,
right_obj,
right_out,
MappingSymbol::Left(left_name),
diff_config,
)?;
}
}
Ok(DiffObjsResult {
left: left.map(|(_, o)| o),
right: right.map(|(_, o)| o),
prev: prev.map(|(_, o)| o),
})
}
#[derive(Clone, Copy)]
enum MappingSymbol<'a> {
Left(&'a str),
Right(&'a str),
}
/// When we're selecting a symbol to use as a comparison, we'll create comparisons for all
/// symbols in the other object that match the selected symbol's section and kind. This allows
/// us to display match percentages for all symbols in the other object that could be selected.
fn generate_mapping_symbols(
left_obj: &Object,
left_out: &mut ObjectDiff,
right_obj: &Object,
right_out: &mut ObjectDiff,
mapping_symbol: MappingSymbol,
config: &DiffObjConfig,
) -> Result<()> {
let (base_obj, base_name, target_obj) = match mapping_symbol {
MappingSymbol::Left(name) => (left_obj, name, right_obj),
MappingSymbol::Right(name) => (right_obj, name, left_obj),
};
let Some(base_symbol_ref) = base_obj.symbol_by_name(base_name) else {
return Ok(());
};
let base_section_kind = symbol_section_kind(base_obj, &base_obj.symbols[base_symbol_ref]);
for (target_symbol_index, target_symbol) in target_obj.symbols.iter().enumerate() {
if target_symbol.size == 0
|| target_symbol.flags.contains(SymbolFlag::Ignored)
|| symbol_section_kind(target_obj, target_symbol) != base_section_kind
{
continue;
}
let (left_symbol_idx, right_symbol_idx) = match mapping_symbol {
MappingSymbol::Left(_) => (base_symbol_ref, target_symbol_index),
MappingSymbol::Right(_) => (target_symbol_index, base_symbol_ref),
};
let (left_diff, right_diff) = match base_section_kind {
SectionKind::Code => {
diff_code(left_obj, right_obj, left_symbol_idx, right_symbol_idx, config)
}
SectionKind::Data => {
diff_data_symbol(left_obj, right_obj, left_symbol_idx, right_symbol_idx)
}
SectionKind::Bss | SectionKind::Common => {
diff_bss_symbol(left_obj, right_obj, left_symbol_idx, right_symbol_idx)
}
SectionKind::Unknown => continue,
}?;
match mapping_symbol {
MappingSymbol::Left(_) => right_out.mapping_symbols.push(MappingSymbolDiff {
symbol_index: right_symbol_idx,
symbol_diff: right_diff,
}),
MappingSymbol::Right(_) => left_out
.mapping_symbols
.push(MappingSymbolDiff { symbol_index: left_symbol_idx, symbol_diff: left_diff }),
}
}
Ok(())
}
#[derive(Copy, Clone, Eq, PartialEq)]
struct SymbolMatch {
left: Option<usize>,
right: Option<usize>,
prev: Option<usize>,
section_kind: SectionKind,
}
#[derive(Copy, Clone, Eq, PartialEq)]
struct SectionMatch {
left: Option<usize>,
right: Option<usize>,
section_kind: SectionKind,
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(default))]
pub struct MappingConfig {
/// Manual symbol mappings
pub mappings: BTreeMap<String, String>,
/// The right object symbol name that we're selecting a left symbol for
pub selecting_left: Option<String>,
/// The left object symbol name that we're selecting a right symbol for
pub selecting_right: Option<String>,
}
fn apply_symbol_mappings(
left: &Object,
right: &Object,
mapping_config: &MappingConfig,
left_used: &mut BTreeSet<usize>,
right_used: &mut BTreeSet<usize>,
matches: &mut Vec<SymbolMatch>,
) -> Result<()> {
// If we're selecting a symbol to use as a comparison, mark it as used
// This ensures that we don't match it to another symbol at any point
if let Some(left_name) = &mapping_config.selecting_left
&& let Some(left_symbol) = left.symbol_by_name(left_name)
{
left_used.insert(left_symbol);
}
if let Some(right_name) = &mapping_config.selecting_right
&& let Some(right_symbol) = right.symbol_by_name(right_name)
{
right_used.insert(right_symbol);
}
// Apply manual symbol mappings
for (left_name, right_name) in &mapping_config.mappings {
let Some(left_symbol_index) = left.symbol_by_name(left_name) else {
continue;
};
if left_used.contains(&left_symbol_index) {
continue;
}
let Some(right_symbol_index) = right.symbol_by_name(right_name) else {
continue;
};
if right_used.contains(&right_symbol_index) {
continue;
}
let left_section_kind = left
.symbols
.get(left_symbol_index)
.and_then(|s| s.section)
.and_then(|section_index| left.sections.get(section_index))
.map_or(SectionKind::Unknown, |s| s.kind);
let right_section_kind = right
.symbols
.get(right_symbol_index)
.and_then(|s| s.section)
.and_then(|section_index| right.sections.get(section_index))
.map_or(SectionKind::Unknown, |s| s.kind);
if left_section_kind != right_section_kind {
log::warn!(
"Symbol section kind mismatch: {left_name} ({left_section_kind:?}) vs {right_name} ({right_section_kind:?})"
);
continue;
}
matches.push(SymbolMatch {
left: Some(left_symbol_index),
right: Some(right_symbol_index),
prev: None, // TODO
section_kind: left_section_kind,
});
left_used.insert(left_symbol_index);
right_used.insert(right_symbol_index);
}
Ok(())
}
/// Find matching symbols between each object.
fn matching_symbols(
left: Option<&Object>,
right: Option<&Object>,
prev: Option<&Object>,
mappings: &MappingConfig,
) -> Result<Vec<SymbolMatch>> {
let mut matches = Vec::new();
let mut left_used = BTreeSet::new();
let mut right_used = BTreeSet::new();
if let Some(left) = left {
if let Some(right) = right {
apply_symbol_mappings(
left,
right,
mappings,
&mut left_used,
&mut right_used,
&mut matches,
)?;
}
// Do two passes for nameless literals. The first only pairs up perfect matches to ensure
// those are correct first, while the second pass catches near matches.
for fuzzy_literals in [false, true] {
for (symbol_idx, symbol) in left.symbols.iter().enumerate() {
if symbol.size == 0 || symbol.flags.contains(SymbolFlag::Ignored) {
continue;
}
let section_kind = symbol_section_kind(left, symbol);
if section_kind == SectionKind::Unknown {
continue;
}
if left_used.contains(&symbol_idx) {
continue;
}
let symbol_match = SymbolMatch {
left: Some(symbol_idx),
right: find_symbol(right, left, symbol_idx, Some(&right_used), fuzzy_literals),
prev: find_symbol(prev, left, symbol_idx, None, fuzzy_literals),
section_kind,
};
matches.push(symbol_match);
if let Some(right) = symbol_match.right {
left_used.insert(symbol_idx);
right_used.insert(right);
}
}
}
}
if let Some(right) = right {
// Do two passes for nameless literals. The first only pairs up perfect matches to ensure
// those are correct first, while the second pass catches near matches.
for fuzzy_literals in [false, true] {
for (symbol_idx, symbol) in right.symbols.iter().enumerate() {
if symbol.size == 0 || symbol.flags.contains(SymbolFlag::Ignored) {
continue;
}
let section_kind = symbol_section_kind(right, symbol);
if section_kind == SectionKind::Unknown {
continue;
}
if right_used.contains(&symbol_idx) {
continue;
}
let symbol_match = SymbolMatch {
left: None,
right: Some(symbol_idx),
prev: find_symbol(prev, right, symbol_idx, None, fuzzy_literals),
section_kind,
};
matches.push(symbol_match);
if symbol_match.prev.is_some() {
right_used.insert(symbol_idx);
}
}
}
}
Ok(matches)
}
fn unmatched_symbols<'obj, 'used>(
obj: &'obj Object,
used: Option<&'used BTreeSet<usize>>,
) -> impl Iterator<Item = (usize, &'obj Symbol)> + 'used
where
'obj: 'used,
{
obj.symbols.iter().enumerate().filter(move |&(symbol_idx, symbol)| {
!symbol.flags.contains(SymbolFlag::Ignored)
// Skip symbols that have already been matched
&& !used.is_some_and(|u| u.contains(&symbol_idx))
})
}
fn symbol_section<'obj>(obj: &'obj Object, symbol: &Symbol) -> Option<(&'obj str, SectionKind)> {
if let Some(section) = symbol.section.and_then(|section_idx| obj.sections.get(section_idx)) {
// Match x86 .rdata$r against .rdata$rs
let section_name =
section.name.split_once('$').map_or(section.name.as_str(), |(prefix, _)| prefix);
Some((section_name, section.kind))
} else if symbol.flags.contains(SymbolFlag::Common) {
Some((".comm", SectionKind::Common))
} else {
None
}
}
fn symbol_section_kind(obj: &Object, symbol: &Symbol) -> SectionKind {
match symbol.section {
Some(section_index) => obj.sections[section_index].kind,
None if symbol.flags.contains(SymbolFlag::Common) => SectionKind::Common,
None => SectionKind::Unknown,
}
}
fn find_symbol(
obj: Option<&Object>,
in_obj: &Object,
in_symbol_idx: usize,
used: Option<&BTreeSet<usize>>,
fuzzy_literals: bool,
) -> Option<usize> {
let in_symbol = &in_obj.symbols[in_symbol_idx];
let obj = obj?;
let (section_name, section_kind) = symbol_section(in_obj, in_symbol)?;
// Match compiler-generated symbols against each other (e.g. @251 -> @60)
// If they are in the same section and have the same value
if in_symbol.flags.contains(SymbolFlag::CompilerGenerated)
&& matches!(section_kind, SectionKind::Code | SectionKind::Data | SectionKind::Bss)
{
let mut closest_match_symbol_idx = None;
let mut closest_match_percent = 0.0;
for (symbol_idx, symbol) in unmatched_symbols(obj, used) {
let Some(section_index) = symbol.section else {
continue;
};
if obj.sections[section_index].name != section_name {
continue;
}
if !symbol.flags.contains(SymbolFlag::CompilerGenerated) {
continue;
}
match section_kind {
SectionKind::Data | SectionKind::Code => {
// For code or data, pick the first symbol with exactly matching bytes and relocations.
// If no symbols match exactly, and `fuzzy_literals` is true, pick the closest
// plausible match instead.
if let Ok((left_diff, _right_diff)) =
diff_data_symbol(in_obj, obj, in_symbol_idx, symbol_idx)
&& let Some(match_percent) = left_diff.match_percent
&& (match_percent == 100.0
|| (fuzzy_literals
&& match_percent >= 50.0
&& match_percent > closest_match_percent))
{
closest_match_symbol_idx = Some(symbol_idx);
closest_match_percent = match_percent;
if match_percent == 100.0 {
break;
}
}
}
SectionKind::Bss => {
// For BSS, pick the first symbol that has the exact matching size.
if in_symbol.size == symbol.size {
closest_match_symbol_idx = Some(symbol_idx);
break;
}
}
_ => unreachable!(),
}
}
return closest_match_symbol_idx;
}
// Try to find a symbol with a matching name
if let Some((symbol_idx, _)) = unmatched_symbols(obj, used).find(|&(_, symbol)| {
symbol_name_matches(in_symbol, symbol)
&& symbol_section_kind(obj, symbol) == section_kind
&& symbol_section(obj, symbol).is_some_and(|(name, _)| name == section_name)
}) {
return Some(symbol_idx);
}
None
}
/// Find matching sections between each object.
fn matching_sections(left: Option<&Object>, right: Option<&Object>) -> Result<Vec<SectionMatch>> {
let mut matches = Vec::with_capacity(
left.as_ref()
.map_or(0, |o| o.sections.len())
.max(right.as_ref().map_or(0, |o| o.sections.len())),
);
if let Some(left) = left {
for (section_idx, section) in left.sections.iter().enumerate() {
if section.kind == SectionKind::Unknown {
continue;
}
matches.push(SectionMatch {
left: Some(section_idx),
right: find_section(right, §ion.name, section.kind, &matches),
section_kind: section.kind,
});
}
}
if let Some(right) = right {
for (section_idx, section) in right.sections.iter().enumerate() {
if section.kind == SectionKind::Unknown {
continue;
}
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<&Object>,
name: &str,
section_kind: SectionKind,
matches: &[SectionMatch],
) -> Option<usize> {
obj?.sections.iter().enumerate().position(|(i, s)| {
s.kind == section_kind && s.name == name && !matches.iter().any(|m| m.right == Some(i))
})
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DiffSide {
/// The target/expected side of the diff.
Target,
/// The base side of the diff.
Base,
}