linker-diff 0.8.0

Diffs and validates ELF binaries
Documentation
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
//! The code in this module is responsible for diffing the contents of sections. This is made
//! complicated due to the layouts of the binaries being different. This means that working out what
//! to diff is slightly tricky. Once we are diffing, the contents can be different because of
//! references to symbols that are in different locations in the different binaries. A high level
//! output of how this works follows.
//!
//! We depend on Wild's binary output having a corresponding .layout file. This allows us to know
//! all the input sections that Wild put into the binary and where it put them.
//!
//! We then start by looking for symbols that have exactly one definition in each binary. We can
//! then tie the input section that defined that symbol to its corresponding location in all of the
//! binaries.
//!
//! We then have an input section that came from one of the input files and the location at which
//! each linker placed that input section in their respective binaries. We can now diff the
//! different versions of the section.
//!
//! Diffing the section revolves around the relocations that the original input file listed for that
//! section. We process each relocation in order of offset. The relocation may however not have been
//! applied as listed. Rather, one of several relaxations might have been applied to the relocation.
//! These relaxations generally, but not always change the bytes surrounding the relocation. For
//! each relocation, we check each candidate relaxation, to see if it matches that surrounding
//! bytes. If it doesn't, we eliminate it.
//!
//! We then extract the value of the relocation by reading the bytes at the location of the
//! relocation from the output binary. This location we read from might have been adjusted by the
//! relaxation. Once we have the location, we reverse whatever transformations would have been
//! performed on it by the relocation. If, based on the relocation type, our value is an address, we
//! can then look to see what section the address points to. This allows us to eliminate further
//! relaxations by checking if the address is part of a PLT section or not.
//!
//! It might be tempting to take the address extracted from the binary and look up what is at that
//! address, however this technique leads to false matches, since multiple symbols can point to the
//! same address by coincidence. For example, a symbol that points one byte past the end of a
//! section might point to the same address as a symbol that points to the start of the next
//! section. So instead, we start from the symbol associated with the original relocation and work
//! forward, checking where it is. Provided the symbol is unique, we can then claim to have matched
//! against it.

use self::section_map::FunctionInfo;
use self::section_map::IndexedLayout;
use self::section_map::InputSectionId;
use self::section_map::SymbolInfo;
use crate::Binary;
use crate::Diff;
use crate::DiffValues;
use crate::ElfFile64;
use crate::Report;
use crate::Result;
use crate::SectionCoverage;
use crate::arch::Arch;
use crate::arch::Instruction;
use crate::arch::PltEntry;
use crate::arch::RType;
use crate::arch::Relaxation;
use crate::arch::RelaxationKind;
use crate::diagnostics::TraceOutput;
use crate::get_r_type;
use crate::section_map;
use anyhow::Context as _;
use anyhow::anyhow;
use anyhow::bail;
use anyhow::ensure;
use colored::ColoredString;
use colored::Colorize as _;
use hashbrown::HashMap;
use itertools::Itertools as _;
use linker_utils::elf::BitMask;
use linker_utils::elf::DynamicRelocationKind;
use linker_utils::elf::RelocationKind;
use linker_utils::elf::RelocationKindInfo;
use linker_utils::elf::RelocationSize;
#[allow(clippy::wildcard_imports)]
use linker_utils::elf::secnames::*;
use linker_utils::relaxation::RelocationModifier;
use linker_utils::utils::u32_from_slice;
use object::LittleEndian;
use object::Object as _;
use object::ObjectKind;
use object::ObjectSection as _;
use object::ObjectSymbol as _;
use object::RelocationTarget;
use object::SectionKind;
use object::read::elf::ElfSection64;
use object::read::elf::FileHeader as _;
use object::read::elf::ProgramHeader as _;
use object::read::elf::SectionHeader as _;
use std::fmt::Display;
use std::fmt::Write as _;
use std::iter::Peekable;
use std::ops::Range;

/// Set this environment variable to a function name to show only diffs for that function.
const SHOW_FUNCTION_ENV: &str = "LINKER_DIFF_FOCUS_FUNCTION";

/// The kinds of sections that we support diffing here. Note, some other kinds of sections are
/// diffed elsewhere in linker-diff. e.g. `init_array` and `fini_array`.
const SUPPORTED_SECTION_KINDS: &[SectionKind] = &[SectionKind::Text, SectionKind::Data];

/// Reports differences in sections in particular differences in the relocations that were applied
/// to those sections, although the literal bytes between the relocations are also diffed.
pub(crate) fn report_section_diffs<A: Arch>(report: &mut Report, binaries: &[Binary]) {
    let Some(layout) = binaries[0].indexed_layout.as_ref() else {
        report.add_error("A .layout file is required");
        return;
    };

    // If we got an error building our index, then don't try to diff functions. We'd just get heaps
    // of diffs due to an incomplete index.
    if binaries
        .iter()
        .any(|o| o.address_index.index_error.is_some())
    {
        return;
    }

    if let Some(cov) = report.coverage.as_mut() {
        populate_section_coverage(cov, layout);
    }

    let by_name = symbol_versions_by_name(binaries, layout);
    let matched_sections = unified_sections_from_symbols(report, by_name, layout, binaries);

    let mut section_ids_to_process = matched_sections
        .keys()
        .copied()
        // Sort sections so that we process sections in a deterministic order, since that affects
        // our output order.
        .sorted()
        .collect_vec();

    while let Some(section_id) = section_ids_to_process.pop() {
        let section_versions = matched_sections.get(&section_id).unwrap();

        let section_diff_key = format!(
            "section-diff-failed.{}",
            section_versions
                .original_section(layout)
                .and_then(|s| Ok(s.name()?))
                .unwrap_or("unknown-section")
        );

        if !report.should_ignore(&section_diff_key)
            && let Err(error) = compare_sections::<A>(report, section_versions, binaries, layout)
        {
            report.add_diff(Diff {
                key: section_diff_key,
                values: DiffValues::PreFormatted(error.to_string()),
            });
        }
    }
}

fn compare_sections<A: Arch>(
    report: &mut Report,
    section_versions: &SectionVersions<'_>,
    binaries: &[Binary],
    layout: &IndexedLayout,
) -> Result {
    let original_section = section_versions.original_section(layout)?;

    if let Some(coverage) = report.coverage.as_mut()
        && let Some(sec_cov) = coverage
            .sections
            .get_mut(&section_versions.input_section_id)
    {
        sec_cov.diffed = true;
    }

    // We already filtered input sections based on their kind. Now we filter based on the output
    // section into which the input section was placed. If we don't do this, we're likely to end up
    // diffing input sections like '.ctors' which are often just set to PROGBITS.
    if determine_output_section_kind(binaries, &section_versions.addresses_by_binary)
        .is_some_and(|output_section_kind| !SUPPORTED_SECTION_KINDS.contains(&output_section_kind))
    {
        return Ok(());
    }

    let mut testers = binaries
        .iter()
        .zip(&section_versions.addresses_by_binary)
        .map(|(bin, &section_address)| -> Result<RelaxationTester> {
            RelaxationTester::new(
                &original_section,
                bin,
                section_address,
                layout.input_file_for_section(section_versions.input_section_id),
            )
        })
        .collect::<Result<Vec<_>>>()?;

    let section_kind = original_section.kind();

    // We need to process relocations in order since we diff the gaps between the relocations as we
    // go. We can't do that if there might be another relocation between that we just haven't seen
    // yet.
    let mut relocations = original_section.relocations().collect_vec();
    relocations.sort_by_key(|(offset, _)| *offset);

    let mut relocations = relocations.into_iter().peekable();

    while let Some(group) = RelocationGroup::<A>::next(&mut relocations, section_versions, layout)?
    {
        diff_literal_bytes::<A>(
            report,
            section_versions,
            layout,
            &mut testers,
            group
                .start_offset()
                .saturating_sub(A::MAX_RELAX_MODIFY_BEFORE),
        )?;

        // If any tester indicates that the next relocation should be skipped, then either all
        // testers will say to skip, or the previous relocation didn't match. In either case, we
        // want to skip the next relocation.
        if testers
            .iter()
            .any(|t| t.next_modifier == RelocationModifier::SkipNextRelocation)
        {
            testers
                .iter_mut()
                .for_each(|t| t.next_modifier = RelocationModifier::Normal);

            continue;
        }

        let mut resolutions = Vec::new();
        for tester in &mut testers {
            resolutions.push(tester.resolve_group_traced(section_kind, &group));
        }

        // The first resolution (the one from our linker-under-test) must be equal to at least one
        // of the other resolutions.
        if let Some(first) = resolutions.first() {
            let mut trace = TraceOutput::default();

            let at_least_one_match = crate::diagnostics::trace_scope(&mut trace, || {
                resolutions[1..].iter().any(|other| first.matches(other))
            });

            // Ideally we'd successfully match all binaries, however GNU ld when it has PLT
            // relocation for an undefined symbol emits a PLT entry that points to an invalid GOT
            // address. We don't have any good way to match something like that.
            let first_has_match_failure = first.relaxations.is_none() || first.has_error();

            if !at_least_one_match || first_has_match_failure {
                // Check if the diff key would be ignored
                let start_offset = group.start_offset();
                let original_annotations = group.into_original_annotations();
                let bin_attributes = testers[1].bin.address_index.bin_attributes;
                let diff_key =
                    diff_key_for_res_mismatch(&resolutions, &original_annotations, bin_attributes);

                if !report.should_ignore(&diff_key) {
                    let diff = resolution_diff_exec(
                        &diff_key,
                        start_offset,
                        original_annotations,
                        &resolutions,
                        &testers,
                        section_versions.input_section_id,
                        layout,
                        trace,
                    )?;
                    report.add_diff(diff);
                }

                update_offsets_if_match_failed(
                    section_versions,
                    layout,
                    original_section.size(),
                    &mut testers,
                    &resolutions,
                    &mut relocations,
                )?;
            }
        };
    }

    // There are no more relocations. Diff literal bytes up to the end of the section.
    diff_literal_bytes::<A>(
        report,
        section_versions,
        layout,
        &mut testers,
        original_section.size(),
    )?;

    Ok(())
}

fn determine_output_section_kind(
    binaries: &[Binary<'_>],
    addresses_by_binary: &[u64],
) -> Option<SectionKind> {
    binaries
        .iter()
        .zip(addresses_by_binary)
        .rev()
        .find_map(|(bin, address)| {
            bin.section_containing_address(*address)
                .map(|section| section.kind())
        })
}

/// If we got a match failure, then advance to the start of the next function, or if there is no
/// next function to the end of the section. This is to avoid getting follow-on errors after a match
/// failure.
fn update_offsets_if_match_failed<A: Arch>(
    section_versions: &SectionVersions<'_>,
    layout: &IndexedLayout<'_>,
    section_size: u64,
    testers: &mut Vec<RelaxationTester<'_>>,
    resolutions: &[ResolvedGroup<'_, A>],
    relocations: &mut Peekable<std::vec::IntoIter<(u64, object::Relocation)>>,
) -> Result {
    if resolutions.iter().any(|r| {
        r.annotations
            .iter()
            .any(|a| matches!(a.kind, AnnotationKind::MatchFailed(..)))
    }) {
        let offset = testers.iter().map(|t| t.previous_end).max().unwrap_or(0);

        let section_info = layout
            .get_section_info(section_versions.input_section_id)
            .context("Attempt to diff missing section")?;

        let new_offset = section_info
            .next_function_offset(offset)
            .unwrap_or(section_size);

        // Update all testers to the new location.
        testers.iter_mut().for_each(|t| t.previous_end = new_offset);

        // Skip any relocations that applied to the addresses we skipped.
        while let Some((next_rel_offset, _rel)) = relocations.peek() {
            if *next_rel_offset < new_offset {
                relocations.next();
            } else {
                break;
            }
        }
    };

    Ok(())
}

struct RelocationGroup<'data, A: Arch> {
    relocations: Vec<InputRelocation<'data, A>>,
}

#[derive(Debug, PartialEq, Eq)]
struct RelaxationGroup<'data, A: Arch> {
    /// Match results for each relocation in the group.
    match_results: Vec<RelaxationMatchResult<'data, A>>,
    is_complete: bool,
}

impl<'data, A: Arch> RelaxationGroup<'data, A> {
    fn start_offset(&self) -> u64 {
        self.match_results
            .iter()
            .map(|r| r.start())
            .min()
            .unwrap_or(0)
    }

    fn end_offset(&self) -> u64 {
        self.match_results
            .iter()
            .map(|r| r.end())
            .max()
            .unwrap_or(0)
    }

    fn first_if_matched(&self) -> Option<&RelaxationMatch<'data, A>> {
        if !self.match_results.iter().all(|m| m.matched()) {
            return None;
        }
        match self.match_results.first()? {
            RelaxationMatchResult::Matched(m) => Some(m),
            _ => None,
        }
    }

    fn eliminate_alt_r_types(&mut self, reference: &Reference<A::RType>) {
        for result in &mut self.match_results {
            if let RelaxationMatchResult::Matched(m) = result
                && let Some(alt_r_type) = m.relaxation.alt_r_type
            {
                // Some relaxations cannot be identified purely by the instruction bytes. For
                // example relaxing a PLT32 to a PC32, the instruction bytes are
                // left the same. All that differs is whether we now point to the
                // PLT or not.

                match (
                    reference.verify_consistent_with_r_type(m.relaxation.new_r_type),
                    reference.verify_consistent_with_r_type(alt_r_type),
                ) {
                    (Err(_), Ok(())) => {
                        m.relaxation.new_r_type = alt_r_type;
                    }
                    (Ok(()), Err(_)) => {
                        m.relaxation.alt_r_type = None;
                    }
                    _ => {}
                }
            }
        }
    }

    fn matches_if_ok(&self) -> Option<Vec<RelaxationMatch<'data, A>>> {
        self.match_results
            .iter()
            .map(|r| match r {
                RelaxationMatchResult::Matched(relaxation_match) => Ok(*relaxation_match),
                _ => Err(()),
            })
            .collect::<Result<Vec<RelaxationMatch<A>>, ()>>()
            .ok()
    }

    fn matches_skipping_nops(&self) -> Vec<&RelaxationMatchResult<'data, A>> {
        self.match_results
            .iter()
            .filter(|result| !matches!(result, RelaxationMatchResult::Matched(m) if m.relaxation.relaxation_kind.is_replace_with_no_op()))
            .collect()
    }
}

impl<'data, A: Arch> RelocationGroup<'data, A> {
    fn into_original_annotations(self) -> Vec<OriginalAnnotation<'data, A>> {
        self.relocations
            .into_iter()
            .map(|r| r.original_annotation)
            .collect()
    }

    fn next(
        relocations_in: &mut Peekable<std::vec::IntoIter<(u64, object::Relocation)>>,
        section_versions: &SectionVersions<'data>,
        layout: &IndexedLayout<'data>,
    ) -> Result<Option<RelocationGroup<'data, A>>> {
        let mut relocations = Vec::new();

        let mut chain = Vec::new();

        while let Some(next_r_type) = relocations_in
            .peek()
            .map(|(_, rel)| get_r_type::<A::RType>(rel))
        {
            chain.push(next_r_type);
            if chain.len() >= 2 && !A::should_chain_relocations(&chain) {
                break;
            }

            let (offset, rel) = relocations_in.next().unwrap();

            let original_annotation =
                get_original_annotation::<A>(section_versions, layout, &rel, offset)?;

            relocations.push(InputRelocation {
                offset,
                rel,
                original_annotation,
            });
        }

        if relocations.is_empty() {
            Ok(None)
        } else {
            Ok(Some(RelocationGroup { relocations }))
        }
    }

    fn start_offset(&self) -> u64 {
        self.relocations[0].offset
    }

    fn is_complete_group(&self) -> bool {
        A::is_complete_chain(self.relocations.iter().map(|r| get_r_type(&r.rel)))
    }
}

struct InputRelocation<'data, A: Arch> {
    offset: u64,

    rel: object::Relocation,

    original_annotation: OriginalAnnotation<'data, A>,
}

impl<'data, A: Arch> InputRelocation<'data, A> {
    fn original_referent(&self) -> Referent<'data, <A as Arch>::RType> {
        self.original_annotation.reference.referent
    }
}

fn get_original_annotation<'data, A: Arch>(
    section_versions: &SectionVersions<'data>,
    layout: &IndexedLayout<'data>,
    rel: &object::Relocation,
    offset: u64,
) -> Result<OriginalAnnotation<'data, A>> {
    let mut orig_trace = TraceOutput::default();

    let original_referent = crate::diagnostics::trace_scope(&mut orig_trace, || {
        get_original_referent(
            rel,
            layout.input_file_for_section(section_versions.input_section_id),
        )
    })?;

    let original_annotation = OriginalAnnotation {
        success: MatchedRelaxation::<A> {
            r_type: get_r_type(rel),
            relaxation_kind: None,
        },
        reference: Reference {
            referent: original_referent,
            indirection: Indirection::default(),
        },
        trace: orig_trace,
        offset,
    };

    Ok(original_annotation)
}

/// Diffs literal bytes up to `end`.
fn diff_literal_bytes<'data, A: Arch>(
    report: &mut Report,
    section_versions: &SectionVersions<'data>,
    layout: &IndexedLayout<'data>,
    testers: &mut [RelaxationTester<'data>],
    end: u64,
) -> Result {
    let start = testers
        .iter()
        .map(|t| t.previous_end)
        .max()
        .unwrap_or_default();

    if end <= start {
        return Ok(());
    }

    let mut ok = true;

    for tester in testers.iter_mut() {
        // If the previous match failed, then the testers might be at different positions,
        // synchronise them.
        tester.previous_end = start;

        if end > tester.previous_end {
            ok &= tester.is_equal_up_to(end);
        }
    }

    if ok {
        // Update all the testers to the new location.
        for tester in testers {
            tester.previous_end = end;
        }
    } else {
        let resolutions = testers
            .iter()
            .map(|_| ResolvedGroup {
                relaxations: None,
                annotations: vec![Annotation {
                    offset_in_section: start,
                    kind: AnnotationKind::<A>::LiteralByteMismatch,
                }],
                reference: Reference::unknown(),
                start,
                end,
                trace: TraceOutput::default(),
            })
            .collect_vec();

        let key = diff_key_for_res_mismatch(
            &resolutions,
            &[],
            testers[1].bin.address_index.bin_attributes,
        );
        if !report.should_ignore(&key) {
            report.add_diff(resolution_diff_exec(
                &key,
                end,
                vec![],
                &resolutions,
                testers,
                section_versions.input_section_id,
                layout,
                TraceOutput::default(),
            )?);
        }
    }

    Ok(())
}

/// Represents a diff found in executable code.
struct ExecDiff<'data, A: Arch> {
    offset: u64,
    original_annotations: Vec<OriginalAnnotation<'data, A>>,
    resolutions: &'data [ResolvedGroup<'data, A>],
    testers: &'data [RelaxationTester<'data>],
    section_id: InputSectionId,
    trace: TraceOutput,
}

impl<A: Arch> ExecDiff<'_, A> {
    fn write_to(&self, f: &mut String, layout: &IndexedLayout) -> Result {
        let original_section = layout.get_elf_section(self.section_id)?;
        let file_identifier = layout.input_filename_for_section(self.section_id);

        let function_info = layout
            .get_section_info(self.section_id)
            .context("Attempted to diff a section that wasn't emitted")?
            .function_at_offset(self.offset, layout)?;

        // We'll print all instructions that overlap with this range.
        let range = self.resolutions.iter().map(|r| r.start).min().unwrap_or(0)
            ..self.resolutions.iter().map(|r| r.end).max().unwrap_or(0);

        // Print common information.
        writeln!(
            f,
            "{file_identifier} {section_name} {function_name}",
            section_name = original_section.name()?.blue(),
            function_name = String::from_utf8_lossy(function_info.name).cyan()
        )?;

        let mut trace = TraceOutput::default();

        let annotations = self
            .original_annotations
            .iter()
            .map(|orig| {
                let annotation = Annotation {
                    offset_in_section: orig.offset,
                    kind: AnnotationKind::MatchedRelaxation(orig.success.clone()),
                };

                trace.append(orig.trace.clone());

                annotation
            })
            .collect_vec();

        let mut blocks = vec![RelocationInstructionBlock {
            name: ORIG,
            annotations,
            reference: self.original_annotations.last().map(|a| a.reference),
            trace_messages: Vec::new(),
            section_bytes: original_section.data().ok(),
            section_size: original_section.size(),
            section_address: 0,
            range: range.start..range.end,
            function_info,
            instructions: Default::default(),
            trace,
        }];

        for (res, tester) in self.resolutions.iter().zip(self.testers) {
            let section_bytes = tester.section_bytes;

            let block = RelocationInstructionBlock {
                name: &tester.bin.name,
                annotations: res.annotations.clone(),
                reference: Some(res.reference),
                trace_messages: tester.bin.trace.messages_in(
                    range.start + tester.section_address..range.end + tester.section_address,
                ),
                section_bytes,
                section_size: tester.section_size,
                section_address: tester.section_address,
                range: range.start..range.end,
                function_info,
                instructions: Default::default(),
                trace: res.trace.clone(),
            };

            blocks.push(block);
        }

        if original_section.kind() == SectionKind::Text {
            for block in &mut blocks {
                let mut trace = TraceOutput::default();

                crate::diagnostics::trace_scope(&mut trace, || {
                    block.decode_instructions();
                });

                block.trace.append(trace);
            }
        }

        let maximum_widths = blocks.iter().fold(ColumnWidths::default(), |widths, b| {
            widths.merge(b.widths())
        });

        for block in &blocks {
            block.write_to(f, &maximum_widths)?;
        }

        for message in &self.trace.messages {
            write!(f, "    {message}")?;
        }

        Ok(())
    }
}

/// Produces a diff showing the different resolutions found for a relocation in some executable
/// code.
fn resolution_diff_exec<A: Arch>(
    key: &str,
    offset: u64,
    original_annotations: Vec<OriginalAnnotation<A>>,
    resolutions: &[ResolvedGroup<A>],
    testers: &[RelaxationTester<'_>],
    section_id: InputSectionId,
    layout: &IndexedLayout,
    trace: TraceOutput,
) -> Result<Diff> {
    let diff = ExecDiff {
        offset,
        original_annotations,
        resolutions,
        testers,
        section_id,
        trace,
    };

    let mut out = String::new();
    diff.write_to(&mut out, layout)?;

    Ok(Diff {
        key: key.to_string(),
        values: DiffValues::PreFormatted(out),
    })
}

/// Returns information about what the original relocation refers to.
fn get_original_referent<'data, R: RType>(
    rel: &object::Relocation,
    input_file: &crate::section_map::InputFile<'data>,
) -> Result<Referent<'data, R>> {
    if let RelocationTarget::Symbol(symbol_index) = rel.target() {
        let symbol = input_file.elf_file.symbol_by_index(symbol_index)?;

        if let Some(section_index) = symbol.section_index() {
            let section = input_file.elf_file.section_by_index(section_index)?;

            let flags = section.elf_section_header().sh_flags(LittleEndian) as u32;

            if flags & object::elf::SHF_MERGE != 0 && flags & object::elf::SHF_STRINGS != 0 {
                let section_data = section.data()?;
                let string_plus_rest = &section_data[symbol.address() as usize..];
                if let Some(end_offset) = memchr::memchr(0, string_plus_rest) {
                    let addend = symbol
                        .name_bytes()
                        .is_ok_and(|name| !name.is_empty())
                        .then(|| rel.addend());

                    return Ok(Referent::MergedString(MergedStringRef {
                        data: &string_plus_rest[..end_offset],
                        named_symbol_addend: addend,
                    }));
                }
            }
        }

        let name_bytes = symbol.name_bytes()?;

        let name = SymbolName {
            bytes: name_bytes,
            version: None,
        };

        return Ok(Referent::Named(name, rel.addend()));
    }

    Ok(Referent::Unknown)
}

fn diff_key_for_res_mismatch<A: Arch>(
    resolutions: &[ResolvedGroup<A>],
    original_annotations: &[OriginalAnnotation<A>],
    bin_attributes: BinAttributes,
) -> String {
    if resolutions.len() < 2 {
        return "missing-resolutions".to_owned();
    }

    match (
        &resolutions[0].reference.referent,
        &resolutions[1].reference.referent,
    ) {
        (Referent::DynamicRelocation(d), Referent::Undefined(unmatched)) => {
            if d.entry.is_weak && unmatched.address == 0 {
                // The reference linker emitted a null and we emitted a dynamic
                // relocation for a weak symbol.
                return format!("rel.undefined-weak.dynamic.{}", d.r_type);
            }
        }
        (Referent::DynamicRelocation(ours), Referent::DynamicRelocation(theirs)) => {
            if !resolutions[0].reference.indirection.is_via_plt()
                && resolutions[1].reference.indirection.is_via_plt()
                && ours.addend == 0
                && theirs.addend == 0
                && ours.entry == theirs.entry
            {
                // We used an in-place relocation where the reference linker emitted the address of
                // a PLT entry for the same symbol.
                return "rel.dynamic-plt-bypass".to_owned();
            }
        }
        (Referent::Named(ours, _), Referent::Undefined(_)) => {
            // We defined a symbol that the reference linker didn't.
            return format!("rel.extra-symbol.{ours}");
        }
        (Referent::Named(_, _), Referent::DynamicRelocation(_)) => {
            if resolutions[0].reference.indirection == Indirection::Got
                && resolutions[1].reference.indirection == Indirection::Got
            {
                return format!("rel.missing-got-dynamic.{}", bin_attributes.output_kind);
            }
        }
        _ => {}
    }

    if resolutions[0]
        .reference
        .referent
        .matches(resolutions[1].reference.referent)
        && resolutions[0].reference.indirection == Indirection::Got
        && resolutions[1].reference.indirection == Indirection::GotPltGot
    {
        return "rel.missing-got-plt-got".to_owned();
    }

    // We might have failed to match one of the reference linker outputs, so find the first
    // reference linker output that we successfully matched.
    let reference = resolutions
        .iter()
        .skip(1)
        .find_map(|r| r.relaxations.as_ref().and_then(|r| r.first_if_matched()));

    let ours = resolutions[0]
        .relaxations
        .as_ref()
        .and_then(|r| r.first_if_matched());

    match (ours, reference) {
        (Some(r1), Some(r2)) => {
            let Some(orig) = original_annotations.first() else {
                return "missing-original".to_owned();
            };

            match (
                r1.relaxation.relaxation_kind.is_no_op(),
                r2.relaxation.relaxation_kind.is_no_op(),
            ) {
                (true, false) => {
                    format!(
                        "rel.missing-opt.{}.{:?}.{}",
                        orig.success.r_type,
                        r2.relaxation.relaxation_kind,
                        bin_attributes.type_name()
                    )
                }
                (false, true) => {
                    format!(
                        "rel.extra-opt.{}.{:?}.{}",
                        orig.success.r_type,
                        r1.relaxation.relaxation_kind,
                        bin_attributes.type_name()
                    )
                }
                _ => {
                    let ours_is_copy = resolutions[0].reference.referent.is_copy_relocation();
                    let any_others_copy = resolutions[1..]
                        .iter()
                        .any(|r| r.reference.referent.is_copy_relocation());

                    if ours_is_copy && !any_others_copy {
                        format!("rel.extra-copy-relocation.{}", orig.success.r_type)
                    } else if !ours_is_copy && any_others_copy {
                        format!("rel.missing-copy-relocation.{}", orig.success.r_type)
                    } else {
                        format!(
                            "rel.{}.{}",
                            r1.relaxation.new_r_type, r2.relaxation.new_r_type
                        )
                    }
                }
            }
        }
        _ => {
            let failure_kind = |r: &ResolvedGroup<A>| {
                if r.annotations
                    .iter()
                    .any(|a| matches!(a.kind, AnnotationKind::LiteralByteMismatch))
                {
                    Some("literal-byte-mismatch".to_owned())
                } else {
                    r.annotations
                        .iter()
                        .zip(original_annotations)
                        .find_map(|(a, orig)| match &a.kind {
                            AnnotationKind::Ambiguous(_) => Some("rel.multiple_matches".to_owned()),
                            AnnotationKind::MatchFailed(_) => {
                                Some(format!("rel.match_failed.{}", orig.success.r_type))
                            }
                            AnnotationKind::MatchedRelaxation(_) => None,
                            AnnotationKind::LiteralByteMismatch => {
                                unreachable!();
                            }
                            AnnotationKind::Error(e) => Some(e.clone()),
                        })
                }
            };

            failure_kind(&resolutions[0])
                .or(failure_kind(&resolutions[1]))
                .unwrap_or("rel.unknown_failure".to_owned())
        }
    }
}

/// A block of instructions containing a relocation. Only used for display purposes.
struct RelocationInstructionBlock<'data, A: Arch> {
    /// The name to display in the left-side gutter.
    name: &'data str,

    annotations: Vec<Annotation<'data, A>>,

    reference: Option<Reference<'data, A::RType>>,

    trace_messages: Vec<&'data str>,

    /// The bytes of the section.
    section_bytes: Option<&'data [u8]>,

    section_size: u64,

    /// The base address of the section. For input files, this is just zero. This only affects how
    /// addresses are rendered.
    section_address: u64,

    /// The range of bytes within the section that are of interest. All instructions that overlap
    /// with this range will be displayed. This range is based on the maximum extent of all
    /// relaxations for all the input files. It likely won't cover whole instructions.
    range: Range<u64>,

    function_info: FunctionInfo<'data>,

    /// The instructions that we're going to display.
    instructions: Vec<Instruction<'data, A>>,

    trace: TraceOutput,
}

struct OriginalAnnotation<'data, A: Arch> {
    success: MatchedRelaxation<A>,

    trace: TraceOutput,

    offset: u64,

    reference: Reference<'data, A::RType>,
}

#[derive(Clone, Debug)]
struct Annotation<'data, A: Arch> {
    /// The offset of the annotation within the section.
    offset_in_section: u64,

    kind: AnnotationKind<'data, A>,
}

#[derive(Clone, Debug)]
enum AnnotationKind<'data, A: Arch> {
    MatchedRelaxation(MatchedRelaxation<A>),
    Ambiguous(Vec<RelaxationMatch<'data, A>>),
    MatchFailed(Vec<FailedMatch<A>>),
    Error(String),
    LiteralByteMismatch,
}

#[derive(Clone, Debug)]
struct MatchedRelaxation<A: Arch> {
    r_type: A::RType,

    relaxation_kind: Option<<A as Arch>::RelaxationKind>,
}

#[derive(Debug, PartialEq, Eq, Clone)]
enum RelaxationMatchResult<'data, A: Arch> {
    /// We matched to exactly one relaxation.
    Matched(RelaxationMatch<'data, A>),

    /// We failed to match all candidate relaxations. Holds the reasons why each candidate failed.
    AllFailed(Vec<FailedMatch<A>>),

    /// We matched multiple relaxations.
    Ambiguous(Vec<RelaxationMatch<'data, A>>),
}

impl<'data, A: Arch> RelaxationMatchResult<'data, A> {
    fn start(&self) -> u64 {
        match self {
            RelaxationMatchResult::Matched(relaxation_match) => relaxation_match.start,
            RelaxationMatchResult::AllFailed(failed) => {
                failed.iter().map(|m| m.start).min().unwrap_or(0)
            }
            RelaxationMatchResult::Ambiguous(matches) => {
                matches.iter().map(|m| m.start).min().unwrap_or(0)
            }
        }
    }

    fn end(&self) -> u64 {
        match self {
            RelaxationMatchResult::Matched(relaxation_match) => relaxation_match.end,
            RelaxationMatchResult::AllFailed(failed) => {
                failed.iter().map(|m| m.end).max().unwrap_or(0)
            }
            RelaxationMatchResult::Ambiguous(matches) => {
                matches.iter().map(|m| m.end).max().unwrap_or(0)
            }
        }
    }

    fn annotations(&self) -> Vec<Annotation<'data, A>> {
        match self {
            RelaxationMatchResult::Matched(relaxation_match) => {
                vec![relaxation_match.annotation()]
            }
            RelaxationMatchResult::AllFailed(failed_matches) => {
                failed_matches.iter().map(|r| r.annotation()).collect()
            }
            RelaxationMatchResult::Ambiguous(matches) => vec![Annotation {
                offset_in_section: matches.first().unwrap().offset,
                kind: AnnotationKind::Ambiguous(matches.clone()),
            }],
        }
    }

    fn matches(&self, b: &RelaxationMatchResult<'_, A>) -> bool {
        match (self, b) {
            (RelaxationMatchResult::Matched(a_match), RelaxationMatchResult::Matched(b_match)) => {
                a_match.relaxation == b_match.relaxation
            }
            _ => false,
        }
    }

    fn next_modifier(&self) -> RelocationModifier {
        match self {
            RelaxationMatchResult::Matched(m) => m.next_modifier,
            _ => RelocationModifier::Normal,
        }
    }

    fn matched(&self) -> bool {
        matches!(self, RelaxationMatchResult::Matched(_))
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct RelaxationMatch<'data, A: Arch> {
    relaxation: Relaxation<A>,

    /// The extracted value.
    value: u64,

    /// The inclusive start-offset of the bytes covered by this relaxation.
    start: u64,

    /// The exclusive end-offset of the bytes covered by this relaxation.
    end: u64,

    original_referent: Referent<'data, <A as Arch>::RType>,
    addend: i64,
    offset: u64,
    next_modifier: RelocationModifier,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct FailedMatch<A: Arch> {
    candidate: Relaxation<A>,
    reason: String,
    offset: u64,
    start: u64,
    end: u64,
}

impl<A: Arch> FailedMatch<A> {
    fn new(
        candidate: Relaxation<A>,
        reason: String,
        offset: u64,
        start: u64,
        end: u64,
    ) -> FailedMatch<A> {
        FailedMatch {
            candidate,
            reason,
            offset,
            start,
            end,
        }
    }

    fn annotation(&self) -> Annotation<'static, A> {
        Annotation {
            offset_in_section: self.offset,
            kind: AnnotationKind::MatchFailed(vec![self.clone()]),
        }
    }
}

impl<A: Arch> RelocationInstructionBlock<'_, A> {
    fn widths(&self) -> ColumnWidths {
        ColumnWidths {
            name: self.name.len(),
            address: format!("{:x}", self.section_address + self.section_size).len(),
            instruction_bytes: self
                .instructions
                .iter()
                .map(|i| i.bytes.len())
                .max()
                .unwrap_or_default(),
        }
    }

    /// Decodes and stores the instructions that we're going to display.
    fn decode_instructions(&mut self) {
        let Some(section_bytes) = self.section_bytes else {
            return;
        };

        self.instructions = A::decode_instructions_in_range(
            section_bytes,
            self.section_address,
            self.function_info.offset_in_section,
            self.range.clone(),
        );
    }

    fn write_to(&self, f: &mut String, maximum_widths: &ColumnWidths) -> Result {
        let name_width = maximum_widths.name;
        let address_width = maximum_widths.address;

        let mut annotations = self.annotations.iter().peekable();

        for instruction in &self.instructions {
            let instruction_offset = instruction.address() - self.section_address;

            let instruction_end = instruction_offset + instruction.bytes.len() as u64;

            write!(
                f,
                "{:name_width$} 0x{:0address_width$x}: [ ",
                self.name.blue(),
                instruction.address()
            )?;

            // Print instruction bytes.
            let mut offset = instruction.address() - self.section_address;
            for v in instruction.bytes {
                if self.range.contains(&offset) {
                    // Bytes within the range that we would have compared are highlighted yellow,
                    // while bytes outside the range are left in the default colour. This makes it
                    // easier to spot what's going on if our ranges are wrong.
                    write!(f, "{} ", format!("{v:02x}").yellow())?;
                } else {
                    write!(f, "{v:02x} ")?;
                }
                offset += 1;
            }

            let out = A::instruction_to_string(instruction);

            let instruction_padding =
                (maximum_widths.instruction_bytes - instruction.bytes.len()) * 3;

            writeln!(f, "{:instruction_padding$}] {}", "", out.purple())?;

            if let Some(annotation) = annotations.peek()
                && annotation.offset_in_section >= instruction_offset
                && annotation.offset_in_section < instruction_end
            {
                let num_spaces = name_width
                    + address_width
                    + 7
                    + (annotation.offset_in_section - instruction_offset) as usize * 3;

                annotation.write(f, &format!("{:num_spaces$}", ""))?;

                annotations.next();
            }
        }

        if self.instructions.is_empty() {
            write!(
                f,
                "{name:name_width$} 0x{address:0address_width$x}: [ ",
                name = self.name.blue(),
                address = self.section_address + self.range.start,
            )?;

            for i in self.range.clone() {
                let byte = self
                    .section_bytes
                    .and_then(|bytes| bytes.get(i as usize).copied())
                    .unwrap_or(0);

                write!(f, "{} ", format!("{byte:02x}").yellow())?;
            }
            writeln!(f, "]")?;
        }

        // Print any remaining annotations.
        for annotation in annotations {
            let num_spaces = name_width + address_width + 6;
            annotation.write(f, &format!("{:num_spaces$} ", self.name.blue()))?;
        }

        if let Some(r) = self.reference {
            write!(f, "{:name_width$} ", self.name.blue())?;
            r.write_to(f)?;
        }

        writeln!(f)?;

        self.write_traces(f, maximum_widths)?;

        for message in &self.trace.messages {
            writeln!(f, "{:name_width$} {message}", self.name.blue())?;
        }

        Ok(())
    }

    fn write_traces(&self, f: &mut String, maximum_widths: &ColumnWidths) -> Result {
        let name_width = maximum_widths.name;
        let prefix = " TRACE: ";

        for trace in &self.trace_messages {
            writeln!(f, "{:name_width$}{prefix}{trace}", self.name.blue())?;
        }

        Ok(())
    }
}

impl<A: Arch> Annotation<'_, A> {
    fn write(&self, f: &mut String, line_prefix: &str) -> Result {
        match &self.kind {
            AnnotationKind::MatchedRelaxation(inner) => {
                inner.write_to(f, line_prefix)?;
                writeln!(f)?;
            }
            AnnotationKind::Ambiguous(possible) => {
                for a in possible {
                    a.write_to(f, line_prefix)?;
                    writeln!(f)?;
                }
            }
            AnnotationKind::MatchFailed(failures) => {
                for m in failures {
                    write!(f, "{line_prefix}")?;
                    m.write_to(f)?;
                    writeln!(f)?;
                }
            }
            AnnotationKind::Error(error) => {
                writeln!(f, "{line_prefix}{}", error.red())?;
            }
            AnnotationKind::LiteralByteMismatch => {
                return Ok(());
            }
        }

        Ok(())
    }
}

impl<A: Arch> MatchedRelaxation<A> {
    fn write_to(&self, f: &mut String, line_prefix: &str) -> Result {
        write!(f, "{line_prefix}")?;
        write_carets_for_r_type(f, self.r_type)?;
        write!(f, "{} ", self.r_type.to_string().green())?;
        if let Some(r) = self.relaxation_kind {
            write!(f, "{} ", format!("{r:?}").bright_green())?;
        }

        Ok(())
    }
}

impl<'data, A: Arch> RelaxationMatch<'data, A> {
    fn write_to(&self, f: &mut String, line_prefix: &str) -> Result {
        let rel = self.relaxation;

        write!(f, "{line_prefix}")?;
        write_carets_for_r_type(f, rel.new_r_type)?;

        write!(f, "{} ", rel.new_r_type.to_string().green())?;

        if let Some(alt) = rel.alt_r_type {
            write!(f, "/{} ", alt.to_string().green())?;
        }

        writeln!(
            f,
            "{} ",
            format!("{:?}", rel.relaxation_kind).bright_green()
        )?;

        Ok(())
    }

    fn annotation(&self) -> Annotation<'data, A> {
        Annotation {
            offset_in_section: self.offset,
            kind: AnnotationKind::MatchedRelaxation(MatchedRelaxation {
                r_type: self.relaxation.new_r_type,
                relaxation_kind: Some(self.relaxation.relaxation_kind),
            }),
        }
    }
}

fn write_carets_for_r_type<R: RType>(f: &mut String, r_type: R) -> Result {
    let num_carets = num_carets_for_r_type(r_type);
    write!(f, "{:^<num_carets$} ", "")?;
    Ok(())
}

fn num_carets_for_r_type<R: RType>(r_type: R) -> usize {
    let relocation_size = r_type.opt_relocation_info().map_or(1, relocation_num_bytes);
    (relocation_size * 3).saturating_sub(1).max(1)
}

impl<A: Arch> FailedMatch<A> {
    fn write_to(&self, f: &mut String) -> Result {
        write_carets_for_r_type(f, self.candidate.new_r_type)?;

        write!(
            f,
            "{} {:?} {}",
            self.candidate.new_r_type.to_string().green(),
            self.candidate.relaxation_kind,
            self.reason.red()
        )?;
        Ok(())
    }
}

/// The widths of columns so that we can align stuff.
#[derive(Default, PartialEq, Eq, Clone, Copy)]
struct ColumnWidths {
    name: usize,
    address: usize,
    instruction_bytes: usize,
}

impl ColumnWidths {
    fn merge(&self, other: ColumnWidths) -> ColumnWidths {
        ColumnWidths {
            name: self.name.max(other.name),
            address: self.address.max(other.address),
            instruction_bytes: self.instruction_bytes.max(other.instruction_bytes),
        }
    }
}

#[derive(Debug)]
struct ResolvedGroup<'data, A: Arch> {
    /// The chosen relaxation if we successfully matched to exactly one.
    relaxations: Option<RelaxationGroup<'data, A>>,

    annotations: Vec<Annotation<'data, A>>,

    reference: Reference<'data, A::RType>,

    /// The inclusive start of the bytes associated with this resolution.
    start: u64,

    /// The exclusive end of the bytes associated with this resolution. This should the the offset
    /// of the first byte after the later of (a) any instructions modified by the relaxation and
    /// (b) the bytes of the relocation offset.
    end: u64,

    trace: TraceOutput,
}

impl<A: Arch> ResolvedGroup<'_, A> {
    /// Returns whether two resolutions from different objects files match. Like equality, but only
    /// looks at the parts of the resolution that are expected to match.
    fn matches(&self, other: &ResolvedGroup<A>) -> bool {
        relaxations_match(self.relaxations.as_ref(), other.relaxations.as_ref())
            && self.reference.matches(other.reference)
    }

    fn has_error(&self) -> bool {
        self.annotations
            .iter()
            .any(|a| matches!(a.kind, AnnotationKind::Error(_)))
    }
}

fn relaxations_match<A: Arch>(
    group1: Option<&RelaxationGroup<'_, A>>,
    group2: Option<&RelaxationGroup<'_, A>>,
) -> bool {
    match (group1, group2) {
        (None, None) => true,
        (Some(_), None) => false,
        (None, Some(_)) => false,
        (Some(a), Some(b)) => {
            // Ignore replace with NOP relaxations.
            let a_match_results = a.matches_skipping_nops();
            let b_match_results = b.matches_skipping_nops();

            if a_match_results.len() != b_match_results.len() {
                return false;
            }

            a_match_results
                .iter()
                .zip(&b_match_results)
                .all(|(a, b)| a.matches(b))
        }
    }
}

/// Information about a thing that we reference and how it was referenced.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Reference<'data, R: RType> {
    referent: Referent<'data, R>,

    /// How we got to the referent.
    indirection: Indirection,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum Indirection {
    #[default]
    Direct,
    Got,
    PltGot,
    GotPltGot,
}

impl Indirection {
    fn is_via_plt(self) -> bool {
        matches!(self, Indirection::PltGot)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Referent<'data, R: RType> {
    Unknown,

    /// We have a name for the thing we reference. Second value is an offset from that name in case
    /// we're not pointing directly to it.
    Named(SymbolName<'data>, i64),

    /// Like `Named`, but where the symbol has been copy relocated.
    Copy(SymbolName<'data>, i64),

    DynamicRelocation(DynamicRelocation<'data, R>),

    UnmatchedAddress(UnmatchedAddress),
    UnmatchedTlsOffset(i64),

    /// Like `UnmatchedAddress` but where the original referent is not defined in our output file,
    /// either because it really is undefined, or because it's a local like `.Ldata1` that is
    /// generally not included in the symbol table.
    Undefined(UnmatchedAddress),

    Absolute(u64),

    MergedString(MergedStringRef<'data>),

    /// A reference to an ifunc.
    IFunc(Option<SymbolName<'data>>),

    TlsGd(SymtabEntryInfo<'data>),
    TlsModuleId,
    TlsDescCall,
    TlsDesc(SymtabEntryInfo<'data>),

    /// No relocation is applied. This is used for example when a TLSLD relocation is optimised
    /// away.
    NoRelocation,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MergedStringRef<'data> {
    data: &'data [u8],

    /// An addend applied to the string after determining which string we're working with. Only
    /// present when our string reference is via a named symbol. For unnamed symbols (section
    /// references), the addend is assumed to be applied before determining which string we're
    /// referencing.
    named_symbol_addend: Option<i64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct UnmatchedAddress {
    address: u64,
    reason: &'static str,
}

impl<'data, R: RType> Reference<'data, R> {
    fn write_to(&self, f: &mut String) -> Result {
        match self.indirection {
            Indirection::Direct => {}
            Indirection::Got => write!(f, "GOT{}", arrow())?,
            Indirection::PltGot => write!(f, "PLT{}GOT{}", arrow(), arrow())?,
            Indirection::GotPltGot => write!(f, "GOT{}PLT{}GOT{}", arrow(), arrow(), arrow())?,
        }

        self.referent.write_to(f)?;

        Ok(())
    }

    fn matches(self, other: Reference<'_, R>) -> bool {
        self.indirection == other.indirection && self.referent.matches(other.referent)
    }

    fn verify_consistent_with_r_type(&self, new_r_type: R) -> Result<()> {
        let rel_info = new_r_type.relocation_info()?;

        match rel_info.kind {
            RelocationKind::PltRelative | RelocationKind::PltRelGotBase => {
                if !self.indirection.is_via_plt() {
                    bail!("PLT relocation with non-PLT address");
                }
            }
            _ => {
                if self.indirection.is_via_plt() {
                    bail!("Non-PLT relocation with PLT address");
                }
            }
        }

        Ok(())
    }

    fn unknown() -> Reference<'data, R> {
        Reference {
            referent: Referent::Unknown,
            indirection: Default::default(),
        }
    }
}

impl<R: RType> Referent<'_, R> {
    fn write_to(&self, f: &mut String) -> Result {
        match self {
            Referent::Unknown => write!(f, "??")?,
            Referent::Named(symbol_name, offset) => {
                write!(f, "{symbol_name}")?;

                if *offset != 0 {
                    write!(f, " {offset:+}")?;
                }
            }
            Referent::Copy(symbol_name, offset) => {
                write!(f, "COPY({symbol_name}")?;

                if *offset != 0 {
                    write!(f, " {offset:+}")?;
                }

                write!(f, ")")?;
            }
            Referent::UnmatchedAddress(unmatched) | Referent::Undefined(unmatched) => {
                unmatched.write_to(f)?;
            }
            Referent::UnmatchedTlsOffset(offset) => {
                write!(f, "UnmatchedTlsOffset({offset})")?;
            }
            Referent::Absolute(value) => {
                write!(f, "#0x{value:x}")?;
            }
            Referent::MergedString(merged) => {
                merged.write_to(f)?;
            }
            Referent::DynamicRelocation(dynamic_relocation) => dynamic_relocation.write_to(f)?,
            Referent::TlsDesc(symbol) => write!(f, "TlsDesc({symbol})")?,
            Referent::IFunc(Some(symbol)) => write!(f, "IFunc({symbol})")?,
            Referent::IFunc(None) => write!(f, "UnknownIFunc")?,
            Referent::TlsModuleId => write!(f, "TlsModuleId")?,
            Referent::TlsGd(symbol) => write!(f, "TlsGd({symbol})")?,
            Referent::TlsDescCall => write!(f, "TlsDescCall")?,
            Referent::NoRelocation => write!(f, "NoRelocation")?,
        }

        Ok(())
    }

    fn matches(self, other: Referent<'_, R>) -> bool {
        match (self, other) {
            (Referent::Undefined(_), Referent::Undefined(_)) => {
                // We don't yet support matching things that don't have symbol names. So long as
                // both files don't have a name for something, we accept it.
                true
            }
            (Referent::DynamicRelocation(a), Referent::DynamicRelocation(b)) => a.matches(b),
            _ => self == other,
        }
    }

    fn is_copy_relocation(&self) -> bool {
        matches!(self, Referent::Copy(..))
    }
}

impl MergedStringRef<'_> {
    fn write_to(&self, f: &mut String) -> Result {
        if let Ok(str) = core::str::from_utf8(self.data) {
            write!(f, "MergedString({str:?})")?;
        } else {
            write!(f, "MergedString(InvalidUtf8({:?}))", self.data)?;
        }

        if let Some(addend) = self.named_symbol_addend {
            write!(f, "{addend:+}")?;
        }

        Ok(())
    }
}

impl UnmatchedAddress {
    fn write_to(&self, f: &mut String) -> Result {
        write!(f, "0x{:x} ({})", self.address, self.reason)?;

        Ok(())
    }
}

impl<R: RType> DynamicRelocation<'_, R> {
    fn matches(self, other: DynamicRelocation<'_, R>) -> bool {
        self.normalised() == other.normalised()
    }

    fn normalised(self) -> Self {
        let mut out = self;

        // Other linkers appear to emit jump slot relocations even when `-z now` is passed, whereas
        // we emit GLOB_DAT relocations. So we normalise to GLOB_DAT so as to treat them as
        // equivalent.
        if self.r_type.dynamic_relocation_kind() == Some(DynamicRelocationKind::JumpSlot) {
            out.r_type = R::from_dynamic_relocation_kind(DynamicRelocationKind::GotEntry);
        }

        // TODO: Remove this. We currently don't propagate symbol visibility correctly when emitting
        // dynamic symbols.
        out.entry.is_weak = false;

        out
    }
}

impl<R: RType> DynamicRelocation<'_, R> {
    fn write_to(&self, f: &mut String) -> Result {
        write!(
            f,
            "{}{}{}",
            self.r_type.to_string().green().bold(),
            arrow(),
            self.entry.to_string().cyan()
        )?;
        if self.addend != 0 {
            write!(f, " {:+}", self.addend)?;
        }
        Ok(())
    }
}

fn arrow() -> ColoredString {
    "->".bright_yellow()
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) enum BasicValueKind {
    /// The value is a pointer. We can do things like check to see if it's pointing to a PLT or
    /// GOT entry. If we tried to do that with things that weren't pointers, then we might get
    /// false PLT/GOT matches.
    Pointer,

    AbsoluteValue,

    TlsOffset,

    Aarch64TlsOffset,

    TlsGd,

    TlsModuleId,

    TlsDesc,
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum ValueKind {
    Unwrapped(BasicValueKind),
    Got(BasicValueKind),
    OptionalPlt,
}

#[derive(Clone)]
struct RelaxationTester<'data> {
    /// The section data from the original input object.
    original_data: &'data [u8],

    section_address: u64,

    section_bytes: Option<&'data [u8]>,

    section_size: u64,

    /// The exclusive offset of the end of the previous resolution. Bytes from this offset should
    /// be checked when considering the next resolution.
    previous_end: u64,

    /// Indicates whether the next relocation should be skipped. This is used when a relaxation
    /// replaces not only the current relocation, but the next one too. For example when relaxing
    /// TLSGD to initial exec, the second relocation is a call to `__tls_get_addr` that is no
    /// longer needed.
    next_modifier: RelocationModifier,

    bin: &'data Binary<'data>,
}

impl<'data> RelaxationTester<'data> {
    fn new(
        original_section: &ElfSection64<'data, '_, LittleEndian>,
        bin: &'data Binary<'data>,
        section_address: u64,
        input_file: &section_map::InputFile,
    ) -> Result<Self> {
        let section_len = original_section.size();
        let section_kind = original_section.kind();

        let section_bytes;

        match section_kind {
            SectionKind::UninitializedData | SectionKind::UninitializedTls | SectionKind::Tls => {
                section_bytes = None;
            }
            _ => {
                section_bytes = read_bytes(bin.elf_file, section_address, section_len)?;

                if section_bytes.is_none() {
                    bail!(
                        "Couldn't read {section_len} bytes for section `{section}` \
                            from {input_file} at address 0x{section_address:x} \
                            in `{output_path}`",
                        output_path = bin.path.display(),
                        section = original_section.name()?,
                    );
                }
            }
        }

        Ok(RelaxationTester {
            original_data: original_section.data()?,
            section_bytes,
            section_size: original_section.size(),
            previous_end: 0,
            next_modifier: RelocationModifier::Normal,
            bin,
            section_address,
        })
    }

    /// Checks if the bytes in `section_data` match what we'd expect if the candidate relocation
    /// were applied to `original_data`. If it does, returns the value of the symbol used when the
    /// post-relaxation relocation was applied.
    fn match_relaxation<A: Arch>(
        &self,
        candidate: Relaxation<A>,
        rel: &InputRelocation<'data, A>,
    ) -> Result<RelaxationMatch<'data, A>, FailedMatch<A>> {
        let mut offset = rel.offset;
        let relaxation_range = A::relaxation_byte_range(candidate);

        let base_scratch_offset = relaxation_range.offset_shift;
        let copy_start = offset.saturating_sub(base_scratch_offset) as usize;
        let copy_end = copy_start + relaxation_range.num_bytes;
        let end =
            (offset + candidate.relocation_num_bytes().unwrap_or(0) as u64).max(copy_end as u64);

        let failure = move |reason: String| {
            Err(FailedMatch::new(
                candidate,
                reason,
                offset,
                copy_start as u64,
                end,
            ))
        };

        // Relocations need to have been previously sorted by offset.
        if offset < self.previous_end {
            return failure(format!(
                "Relocations out of order or overlap {offset} < {}",
                self.previous_end
            ));
        }

        if offset < relaxation_range.offset_shift {
            // There aren't enough bytes prior to offset in this section for the relaxation to be
            // possible.
            return failure("Not enough bytes prior".into());
        }

        // If our output section has no data (e.g. BSS), then no relaxation can have been applied,
        // since there would be no place to write the byte changes. Also, BSS isn't executable.
        let Some(section_data) = self.section_bytes else {
            return failure("Attempted to diff section without data".into());
        };

        let mut scratch =
            vec![0_u8; (A::MAX_RELAX_MODIFY_BEFORE + A::MAX_RELAX_MODIFY_AFTER) as usize];

        if copy_end > self.original_data.len() {
            return failure("Not enough bytes after".into());
        }

        let copy_len = copy_end - copy_start;
        let scratch = &mut scratch[..copy_len];

        // Copy part of the original input section into our scratch buffer so that we can apply the
        // relaxation to it and see if it matches what's in the output section.
        scratch.copy_from_slice(&self.original_data[copy_start..copy_end]);

        let previous_end = self.previous_end as usize;
        if section_data[previous_end..copy_start] != self.original_data[previous_end..copy_start] {
            // The bytes between the end of the last relocation and the start of the candidate
            // relaxation don't match.
            return Err(FailedMatch::new(
                candidate,
                format!(
                    "Prior bytes didn't match [0x{:x}..0x{:x})",
                    self.section_address + previous_end as u64,
                    self.section_address + copy_start as u64,
                ),
                offset,
                previous_end as u64,
                end,
            ));
        }

        let mut addend = rel.rel.addend();

        // Apply the relaxation to our scratch buffer.
        let mut scratch_offset = base_scratch_offset;
        let next_modifier = A::next_relocation_modifier(candidate.relaxation_kind);
        A::apply_relaxation(
            candidate.relaxation_kind,
            scratch,
            &mut scratch_offset,
            &mut addend,
        );

        let mask = A::relaxation_mask(candidate, scratch_offset as usize);

        // Check to see if the resulting bytes match what's in the output section.
        if !mask.matches(scratch, &section_data[copy_start..copy_end]) {
            return failure(format!(
                "Relaxation output didn't match: {:x?} != {:x?}",
                mask.mask_value(scratch),
                mask.mask_value(&section_data[copy_start..copy_end])
            ));
        }

        // Based on the change in offset when we applied the relaxation, compute the relocation
        // offset.
        offset = copy_start as u64 + scratch_offset;

        let Some(value_bytes) = section_data.get(offset as usize..) else {
            return failure("Invalid relocation offset".into());
        };

        let value = match candidate
            .relocation_size()
            .and_then(|size| read_value(size, value_bytes))
        {
            Ok(v) => v,
            Err(error) => return failure(error.to_string()),
        };

        Ok(RelaxationMatch {
            relaxation: candidate,
            value,
            start: copy_start as u64,
            end,
            original_referent: rel.original_referent(),
            addend,
            offset,
            next_modifier,
        })
    }

    fn read_reference<A: Arch>(
        &self,
        relaxations_matches: &[RelaxationMatch<A>],
    ) -> Result<Reference<'data, A::RType>> {
        let mut merged_value: u64 = 0;
        let mut addend = 0;
        let mut referent = None;

        // Whether all relocations have been optimised away.
        let mut all_none = true;

        let mut value_kind = ValueKind::OptionalPlt;

        // Empty groups are not permitted.
        let last_match = relaxations_matches.last().unwrap();

        for relaxation_match in relaxations_matches {
            // If we get any runtime relocation, then use that. We should generally only see these
            // in data sections (provided text relocations are disabled).
            if let Some(runtime_relocation) = self
                .bin
                .address_index
                .relocation_at_address(self.section_address + relaxation_match.start)
            {
                let r_type = get_r_type(runtime_relocation);

                if let Some(symbol) = self.symtab_entry_for_relocation(runtime_relocation) {
                    return Ok(Reference {
                        referent: Referent::DynamicRelocation(DynamicRelocation {
                            entry: *symbol,
                            r_type,
                            addend: runtime_relocation.addend(),
                        }),
                        indirection: Indirection::Direct,
                    });
                }

                match r_type.dynamic_relocation_kind() {
                    Some(DynamicRelocationKind::Relative) => {
                        merged_value =
                            merged_value.wrapping_add(runtime_relocation.addend() as u64);
                        continue;
                    }
                    Some(DynamicRelocationKind::Irelative) => {
                        return Ok(Reference {
                            referent: Referent::IFunc(determine_ifunc_name(
                                runtime_relocation.addend() as u64,
                                self.bin,
                            )),
                            indirection: Indirection::Direct,
                        });
                    }
                    _ => {
                        bail!("Unhandled dynamic relocation {r_type}");
                    }
                }
            }

            let mut value = relaxation_match.value;

            if relaxation_match
                .relaxation
                .new_r_type
                .should_ignore_when_computing_referent()
            {
                value = 0;
            }

            // We keep the addend separate from the value because we need to handle merged-strings
            // before we apply the addend.
            addend = relaxation_match.addend;

            let offset = relaxation_match.offset;

            let relocation_info = relaxation_match.relaxation.new_r_type.relocation_info()?;

            let relative_to = self.get_relative_to::<A>(offset, relocation_info)?;

            if let Some(kind) =
                value_kind_for_relocation::<A>(relocation_info.kind, &self.bin.address_index)
            {
                value_kind = kind;
            }

            if relocation_info.kind != RelocationKind::None {
                all_none = false;
            }

            match relocation_info.kind {
                RelocationKind::TlsDescCall => {
                    referent = Some(Referent::TlsDescCall);
                }
                _ => {}
            }

            if relative_to != 0 && relocation_num_bytes(relocation_info) == 4 {
                // Our value is actually an i32. Sign-extend it so that negative values behave
                // correctly in the wrapping_add below.
                value = i64::from(value as i32) as u64;
            }

            value = relative_to.wrapping_add(value);

            merged_value = merged_value.wrapping_add(value);
        }

        if all_none {
            referent = Some(Referent::NoRelocation);
        }

        // The relocation info for our primary and alt r-types should be the same for our purposes
        // here.
        let last_relocation_info = last_match.relaxation.new_r_type.relocation_info()?;

        let mut indirection = Indirection::Direct;

        loop {
            match value_kind {
                ValueKind::OptionalPlt => {
                    let pointer = merged_value.wrapping_sub(addend as u64);

                    let got_address = self.bin.address_index.plt_to_got_address::<A>(pointer)?;

                    let Some(got_address) = got_address else {
                        value_kind = ValueKind::Unwrapped(BasicValueKind::Pointer);
                        continue;
                    };

                    if indirection == Indirection::Got {
                        indirection = Indirection::GotPltGot;
                    } else {
                        indirection = Indirection::PltGot;
                    }

                    if !self.bin.address_index.is_got_address(got_address) {
                        bail!(
                            "PLT entry at 0x{pointer:x} points to non-GOT address 0x{got_address:x} in {}",
                            self.bin
                                .section_name_containing_address(got_address)
                                .unwrap_or("??")
                        );
                    }

                    merged_value = got_address;
                    addend = 0;
                    value_kind = ValueKind::Got(BasicValueKind::Pointer);
                }
                ValueKind::Got(inner_kind) => {
                    merged_value = merged_value.wrapping_sub(addend as u64);
                    addend = 0;

                    if !self.bin.address_index.is_got_address(merged_value) {
                        bail!("Expected GOT address, got 0x{merged_value:x}");
                    }

                    if indirection == Indirection::Direct {
                        indirection = Indirection::Got;
                    }

                    let got_entry = self.bin.address_index.dereference_got_address(
                        merged_value,
                        last_relocation_info.kind,
                        self.bin,
                        inner_kind,
                    )?;

                    match got_entry {
                        Referent::UnmatchedAddress(unmatched) => merged_value = unmatched.address,
                        Referent::Absolute(absolute_value)
                            if !self.bin.address_index.is_relocatable() =>
                        {
                            // Our binary is non-relocatable, so we can treat an absolute value like
                            // an address.
                            merged_value = absolute_value;
                        }
                        Referent::UnmatchedTlsOffset(offset) => {
                            merged_value = offset as u64;
                        }
                        other => {
                            referent = Some(other);
                        }
                    }

                    value_kind = ValueKind::Unwrapped(inner_kind);
                }
                ValueKind::Unwrapped(_) => break,
            }
        }

        // We need to handle merged strings after GOT pointers are dereferenced, since it's possible
        // to reference a merged string via the GOT. We also need to handle merged strings before
        // the addend is added, since how we handle the addend with merged strings depends on
        // whether the reference is via a named symbol or not.
        if let Referent::MergedString(orig_merged) = last_match.original_referent {
            referent = Some(self.resolve_merged_string::<A>(
                merged_value,
                last_relocation_info,
                orig_merged,
            )?);
        }

        merged_value = merged_value.wrapping_sub(addend as u64);

        let referent = referent.unwrap_or_else(|| {
            self.resolve_by_symbol_name::<A>(merged_value, last_match.original_referent, value_kind)
        });

        Ok(Reference {
            referent,
            indirection,
        })
    }

    /// Attempts to confirm that `merged_value` is a reference to `original_referent`, or if it
    /// isn't, tells us why.
    fn resolve_by_symbol_name<A: Arch>(
        &self,
        mut merged_value: u64,
        original_referent: Referent<'_, <A as Arch>::RType>,
        expected_value_kind: ValueKind,
    ) -> Referent<'data, <A as Arch>::RType> {
        let reason;

        if let Referent::Named(original_name, original_addend) = original_referent {
            let lookup_result = self.bin.symbol_by_name(original_name.bytes, merged_value);

            match &lookup_result {
                crate::NameLookupResult::Defined(elf_symbol) => {
                    let expected_value = match expected_value_kind {
                        ValueKind::Unwrapped(BasicValueKind::TlsOffset) => {
                            match self.bin.address_index.bin_attributes.output_kind {
                                OutputKind::Executable => {
                                    // The value will have been extracted from a u32, but since it's
                                    // expected to be negative, we need to sign-extend it.
                                    merged_value = i64::from(merged_value as i32) as u64;

                                    // In executable TLS offsets are negative values that are
                                    // relative to the TCB (thread control block), which is
                                    // immediately after the TLS segment, possibly with padding to
                                    // align it to the platforms pointer size.
                                    elf_symbol.address().wrapping_sub(
                                        self.bin
                                            .address_index
                                            .tls_segment_size
                                            .next_multiple_of(size_of::<u64>() as u64),
                                    )
                                }
                                OutputKind::SharedObject => elf_symbol.address(),
                            }
                        }
                        ValueKind::Unwrapped(BasicValueKind::Aarch64TlsOffset) => {
                            // Two words are reserved at the start of the TLS segment for the
                            // runtime.
                            elf_symbol.address() + 2 * 8
                        }
                        _ => elf_symbol.address(),
                    };

                    let offset = merged_value.wrapping_sub(expected_value) as i64;

                    if let Ok(mut bytes) = elf_symbol.name_bytes() {
                        // Strip versions from symbol names, since there are currently
                        // differences between the linkers in terms of whether version names are
                        // added to debug symbols or not. TODO: Look at changing this.
                        if let Some(at_index) = memchr::memchr(b'@', bytes) {
                            bytes = &bytes[..at_index];
                        }

                        if bytes.is_empty() {
                            reason = "Symbol has empty name";
                        } else {
                            let symbol_name = SymbolName {
                                bytes,
                                version: None,
                            };

                            if offset.abs() <= 8 + original_addend.abs() {
                                if has_copy_relocation_for_symbol_named::<A::RType>(
                                    original_name.bytes,
                                    self.bin,
                                ) {
                                    return Referent::Copy(symbol_name, offset);
                                }
                                return Referent::Named(symbol_name, offset);
                            }

                            reason = "symbol is too far away";
                        }
                    } else {
                        reason = "Error reading symbol name";
                    }
                }
                crate::NameLookupResult::Undefined => {
                    reason = "symbol is undefined";
                }
                crate::NameLookupResult::Duplicate => {
                    reason = "symbol has multiple definitions";
                }
            }

            if original_name.bytes.starts_with(b".L")
                || original_name.bytes.is_empty()
                || matches!(lookup_result, crate::NameLookupResult::Undefined)
            {
                return Referent::Undefined(UnmatchedAddress {
                    address: merged_value,
                    reason,
                });
            }
        } else {
            reason = "original symbol has no name";
        }

        Referent::UnmatchedAddress(UnmatchedAddress {
            address: merged_value,
            reason,
        })
    }

    fn resolve_merged_string<A: Arch>(
        &self,
        merged_value: u64,
        last_relocation_info: RelocationKindInfo,
        orig_merged: MergedStringRef<'_>,
    ) -> Result<Referent<'data, <A as Arch>::RType>> {
        let string_address = if let Some(named_symbol_addend) = orig_merged.named_symbol_addend {
            (merged_value as i64 - named_symbol_addend) as u64
        } else if last_relocation_info.kind == RelocationKind::Relative {
            merged_value + A::relocation_to_pc_offset(&last_relocation_info)
        } else {
            merged_value
        };

        let bytes = read_bytes_starting_at(self.bin.elf_file, string_address)
            .ok()
            .flatten()
            .with_context(|| format!("Failed to read bytes starting at 0x{string_address:x}"))?;
        let null_offset = memchr::memchr(0, bytes).with_context(|| {
            format!("Missing null-terminator for merged string starting at 0x{string_address:x}")
        })?;

        Ok(Referent::MergedString(MergedStringRef {
            data: &bytes[..null_offset],
            named_symbol_addend: None,
        }))
    }

    /// Returns the value that a relocation is relative to.
    fn get_relative_to<A: Arch>(
        &self,
        offset: u64,
        relocation_info: RelocationKindInfo,
    ) -> Result<u64> {
        let mut relative_to = match relocation_info.kind {
            RelocationKind::Relative
            | RelocationKind::RelativeRiscVLow12
            | RelocationKind::RelativeLoongArchHigh
            | RelocationKind::PltRelative
            | RelocationKind::TlsGd
            | RelocationKind::TlsLd
            | RelocationKind::TlsDesc
            | RelocationKind::TlsDescLoongArch64
            | RelocationKind::GotTpOff
            | RelocationKind::GotTpOffLoongArch64
            | RelocationKind::GotRelative
            | RelocationKind::GotRelativeLoongArch64 => self.section_address + offset,
            RelocationKind::SymRelGotBase
            | RelocationKind::GotRelGotBase
            | RelocationKind::TlsGdGotBase
            | RelocationKind::GotTpOffGotBase
            | RelocationKind::TlsLdGotBase
            | RelocationKind::TlsDescGotBase
            | RelocationKind::PltRelGotBase => self
                .bin
                .address_index
                .got_base_address
                .context("Missing GOT base address")?,
            RelocationKind::Absolute
            | RelocationKind::AbsoluteSet
            | RelocationKind::AbsoluteSetWord6
            | RelocationKind::AbsoluteAddition
            | RelocationKind::AbsoluteAdditionWord6
            | RelocationKind::AbsoluteSubtraction
            | RelocationKind::AbsoluteSubtractionWord6
            | RelocationKind::Got
            | RelocationKind::TlsGdGot
            | RelocationKind::GotTpOffGot
            | RelocationKind::AbsoluteLowPart
            | RelocationKind::TlsDescGot
            | RelocationKind::TlsLdGot
            | RelocationKind::DtpOff
            | RelocationKind::TpOff
            | RelocationKind::TlsDescCall
            | RelocationKind::PairSubtractionULEB128(..)
            | RelocationKind::None
            | RelocationKind::Alignment => 0,
        };

        relative_to &= A::get_relocation_base_mask(&relocation_info);

        Ok(relative_to)
    }

    fn resolve_group_traced<A: Arch>(
        &mut self,
        section_kind: SectionKind,
        group: &RelocationGroup<'data, A>,
    ) -> ResolvedGroup<'data, A> {
        let mut trace = TraceOutput::default();

        let mut res = crate::diagnostics::trace_scope(&mut trace, || {
            let relaxation_group = self.determine_relaxations(section_kind, group);
            self.resolve_group(relaxation_group)
        });

        res.trace = trace;

        res
    }

    fn determine_relaxations<A: Arch>(
        &mut self,
        section_kind: SectionKind,
        group: &RelocationGroup<'data, A>,
    ) -> RelaxationGroup<'data, A> {
        let match_results = group
            .relocations
            .iter()
            .map(|rel| {
                let r_type = get_r_type(&rel.rel);

                let mut matched_relaxations = Vec::new();
                let mut failed_matches = Vec::new();

                A::possible_relaxations_do(r_type, section_kind, |relaxation| {
                    match self.match_relaxation(relaxation, rel) {
                        Ok(r) => {
                            matched_relaxations.push(r);
                        }
                        Err(failure) => {
                            failed_matches.push(failure);
                        }
                    };
                });

                let m = match matched_relaxations.len() {
                    0 => RelaxationMatchResult::AllFailed(failed_matches),
                    1 => RelaxationMatchResult::Matched(matched_relaxations.pop().unwrap()),
                    _ => RelaxationMatchResult::Ambiguous(matched_relaxations),
                };

                self.accept(&m);

                m
            })
            .collect();

        RelaxationGroup {
            match_results,
            is_complete: group.is_complete_group(),
        }
    }

    fn resolve_group<A: Arch>(
        &self,
        mut relaxation_group: RelaxationGroup<'data, A>,
    ) -> ResolvedGroup<'data, A> {
        let mut reference = None;
        let mut error = None;

        if relaxation_group.is_complete
            && let Some(matches) = relaxation_group.matches_if_ok()
            && matches_are_compatible(&matches)
        {
            match self.read_reference(&matches) {
                Ok(r) => reference = Some(r),
                Err(e) => error = Some(e),
            }
        }

        if let Some(reference) = reference.as_ref() {
            relaxation_group.eliminate_alt_r_types(reference);
        }

        let mut annotations = relaxation_group
            .match_results
            .iter()
            .flat_map(|r| r.annotations())
            .collect_vec();

        if let Some(e) = error {
            annotations.push(Annotation {
                offset_in_section: relaxation_group.end_offset(),
                kind: AnnotationKind::Error(e.to_string()),
            });
        }

        ResolvedGroup {
            start: relaxation_group.start_offset(),
            end: relaxation_group.end_offset(),
            relaxations: Some(relaxation_group),
            annotations,
            reference: reference.unwrap_or(Reference {
                referent: Referent::Unknown,
                indirection: Default::default(),
            }),
            trace: TraceOutput::default(),
        }
    }

    fn accept<A: Arch>(&mut self, matched_relaxation: &RelaxationMatchResult<A>) {
        self.previous_end = matched_relaxation.end();
        self.next_modifier = matched_relaxation.next_modifier();
    }

    /// Returns whether section bytes are equal to the original input file from `self.previous_end`
    /// up to, but not including `offset`.
    fn is_equal_up_to(&self, offset: u64) -> bool {
        (self.section_bytes.is_none() && self.original_data.is_empty())
            || self.section_bytes.is_some_and(|b| {
                b[self.previous_end as usize..offset as usize]
                    == self.original_data[self.previous_end as usize..offset as usize]
            })
    }

    fn symtab_entry_for_relocation(
        &self,
        runtime_relocation: &object::Relocation,
    ) -> Option<&SymtabEntryInfo<'data>> {
        if let object::RelocationTarget::Symbol(symbol_index) = runtime_relocation.target() {
            return self.bin.address_index.dynamic_symbols.get(symbol_index.0);
        }

        None
    }
}

/// Returns whether the matches have the same referent and addend. Our mechanism of grouping
/// relocations is somewhat flawed in that unrelated relocations can end up being grouped if they're
/// adjacent. For now, we ignore any groups where these don't match.
fn matches_are_compatible<A: Arch>(matches: &[RelaxationMatch<'_, A>]) -> bool {
    let mut previous_addend = None;
    let mut previous_referent = None;

    for m in matches {
        if previous_addend.is_some_and(|prev| prev != m.addend) {
            return false;
        }

        if previous_referent.is_some_and(|prev| prev != m.original_referent) {
            return false;
        }

        previous_addend = Some(m.addend);
        previous_referent = Some(m.original_referent);
    }

    true
}

/// Returns what kind of value we can expect when we extract the value written by a relocation.
fn value_kind_for_relocation<A: Arch>(
    relocation_kind: RelocationKind,
    address_index: &AddressIndex,
) -> Option<ValueKind> {
    let kind = match relocation_kind {
        RelocationKind::Absolute
        | RelocationKind::AbsoluteLowPart
        | RelocationKind::AbsoluteSet
        | RelocationKind::AbsoluteSetWord6
        | RelocationKind::AbsoluteAddition
        | RelocationKind::AbsoluteAdditionWord6
        | RelocationKind::AbsoluteSubtraction
        | RelocationKind::AbsoluteSubtractionWord6 => {
            if address_index.is_relocatable() {
                ValueKind::Unwrapped(BasicValueKind::AbsoluteValue)
            } else {
                return None;
            }
        }
        RelocationKind::Relative
        | RelocationKind::RelativeRiscVLow12
        | RelocationKind::RelativeLoongArchHigh
        | RelocationKind::SymRelGotBase => {
            return None;
        }
        RelocationKind::PltRelative | RelocationKind::PltRelGotBase => ValueKind::OptionalPlt,
        RelocationKind::Got
        | RelocationKind::GotRelGotBase
        | RelocationKind::GotRelative
        | RelocationKind::GotRelativeLoongArch64 => ValueKind::Got(BasicValueKind::Pointer),
        RelocationKind::DtpOff => ValueKind::Unwrapped(BasicValueKind::TlsOffset),
        RelocationKind::TpOff => ValueKind::Unwrapped(A::get_basic_value_for_tp_offset()),
        RelocationKind::GotTpOff
        | RelocationKind::GotTpOffLoongArch64
        | RelocationKind::GotTpOffGot
        | RelocationKind::GotTpOffGotBase => ValueKind::Got(BasicValueKind::TlsOffset),
        RelocationKind::TlsDesc
        | RelocationKind::TlsDescLoongArch64
        | RelocationKind::TlsDescGot
        | RelocationKind::TlsDescGotBase => {
            // The TLSDESC structure is stored in the GOT. We should perhaps treat this as
            // Unwrapped(TlsDesc), however the code to read dynamic relocations like TLSDESC is
            // currently in the GOT-dereferencing code.
            ValueKind::Got(BasicValueKind::TlsDesc)
        }
        RelocationKind::TlsLd | RelocationKind::TlsLdGot | RelocationKind::TlsLdGotBase => {
            // Similar to TlsDesc, this is a value stored in the GOT.
            ValueKind::Got(BasicValueKind::TlsModuleId)
        }
        RelocationKind::TlsGd | RelocationKind::TlsGdGot | RelocationKind::TlsGdGotBase => {
            // Same as above.
            ValueKind::Got(BasicValueKind::TlsGd)
        }
        RelocationKind::TlsDescCall
        | RelocationKind::None
        | RelocationKind::PairSubtractionULEB128(..)
        | RelocationKind::Alignment => {
            return None;
        }
    };

    Some(kind)
}

/// Returns a map from symbol name to `SymbolVersions`. This gives us the address of that symbol
/// each file, or tells us that the symbol has 0 or more than 1 definition in at least one file.
fn symbol_versions_by_name<'data>(
    binaries: &'data [Binary<'data>],
    layout: &IndexedLayout<'data>,
) -> HashMap<&'data [u8], SymbolVersions> {
    // Populate our map with eligible unique symbols from the input files.
    let mut by_name: HashMap<&[u8], SymbolVersions> = layout
        .symbol_name_to_section_id
        .iter()
        .filter_map(|(name, symbol_info)| {
            let section = layout.get_elf_section(symbol_info.section_id).ok()?;

            // Merge sections are ignored, since they're split before copying, so can't be compared
            // 1:1 between output files.
            if is_merge_section(&section)
                || section.size() == 0
                || !SUPPORTED_SECTION_KINDS.contains(&section.kind())
            {
                None
            } else {
                let versions = SymbolVersions {
                    original: *symbol_info,
                    addresses_by_binary: Vec::with_capacity(binaries.len()),
                };

                Some((*name, versions))
            }
        })
        .collect();

    // Try to find those same symbols in all the output files.
    for (object_index, obj) in binaries.iter().enumerate() {
        for sym in obj.elf_file.symbols() {
            let Ok(name) = sym.name_bytes() else { continue };

            if let hashbrown::hash_map::Entry::Occupied(mut entry) = by_name.entry(name) {
                if entry.get().addresses_by_binary.len() == object_index {
                    entry.get_mut().addresses_by_binary.push(sym.address());
                } else {
                    // One of the output files didn't define this symbol, remove it from
                    // consideration.
                    entry.remove_entry();
                }
            }
        }
    }

    // Clear any records that are incomplete.
    let num_objects = binaries.len();
    by_name.retain(|_, v| v.addresses_by_binary.len() == num_objects);

    if let Ok(fn_name) = std::env::var(SHOW_FUNCTION_ENV) {
        by_name.retain(|name, _versions| *name == fn_name.as_bytes());
    }

    by_name
}

/// Returns whether the supplied section has the merge flag set. Merge sections aren't copied in
/// their entirety, so need special handling.
fn is_merge_section(section: &ElfSection64<LittleEndian>) -> bool {
    section.elf_section_header().sh_flags(LittleEndian) as u32 & object::elf::SHF_MERGE != 0
}

/// Returns information about sections where we can uniquely locate that section in each input file
/// based on the supplied symbols.
fn unified_sections_from_symbols<'data>(
    report: &mut Report,
    symbol_versions_by_name: HashMap<&'data [u8], SymbolVersions>,
    layout: &IndexedLayout,
    binaries: &[Binary],
) -> HashMap<InputSectionId, SectionVersions<'data>> {
    // Locate the start of the input section for each unique symbol. An input section may contain
    // multiple symbols and we want to make sure that we only diff that section once.

    let mut matched_sections = HashMap::new();

    for (symbol_name, versions) in symbol_versions_by_name {
        let unify_result = unify_symbol_section(
            &mut matched_sections,
            symbol_name,
            versions,
            binaries,
            layout,
        );

        if let Err(error) = unify_result {
            report.add_diff(Diff {
                key: format!("error.{}", String::from_utf8_lossy(symbol_name)),
                values: DiffValues::PreFormatted(error.to_string()),
            });
        }
    }

    matched_sections
}

/// Use `symbol_versions` to populate `matched_sections`.
fn unify_symbol_section<'data>(
    matched_sections: &mut HashMap<InputSectionId, SectionVersions<'data>>,
    symbol_name: &'data [u8],
    mut symbol_versions: SymbolVersions,
    binaries: &[Binary],
    layout: &IndexedLayout,
) -> Result {
    let mut addresses_by_object = core::mem::take(&mut symbol_versions.addresses_by_binary);

    // Ignore ifuncs, since linkers are inconsistent with what the ifunc symbol ends up pointing to.
    if symbol_versions.original.is_ifunc {
        return Ok(());
    }

    // Compute the addresses of the start of the input section in each object by subtracting the
    // offset within the section from each symbol's address.
    for a in &mut addresses_by_object {
        *a = a
            .checked_sub(symbol_versions.original.offset_in_section)
            .context("Underflow when computing section start")?;
    }

    match matched_sections.entry(symbol_versions.original.section_id) {
        hashbrown::hash_map::Entry::Occupied(mut occupied_entry) => {
            let existing = occupied_entry.get_mut();

            existing.verify_consistent(&addresses_by_object, symbol_name, binaries, layout)?;

            // In order to give deterministic reports, we use the first symbol name for a
            // section when sorted alphabetically.
            if symbol_name < existing.found_via_symbol {
                existing.found_via_symbol = symbol_name;
            }
        }
        hashbrown::hash_map::Entry::Vacant(vacant_entry) => {
            vacant_entry.insert(SectionVersions {
                addresses_by_binary: addresses_by_object,
                found_via_symbol: symbol_name,
                input_section_id: symbol_versions.original.section_id,
            });
        }
    }

    Ok(())
}

/// Matches symbols with the same name from each of our input files.
struct SymbolVersions {
    original: SymbolInfo,

    /// The addresses of the symbol in each input file.
    addresses_by_binary: Vec<u64>,
}

/// An input section for which we know where it was placed in each of the binary files.
#[derive(Clone)]
struct SectionVersions<'data> {
    /// The address of this section in each of our binaries.
    addresses_by_binary: Vec<u64>,

    /// The symbol via which we located this section. This is only used for reporting. This may not
    /// be the only or even the first symbol in this section.
    found_via_symbol: &'data [u8],

    input_section_id: InputSectionId,
}

impl<'data> SectionVersions<'data> {
    fn original_section<'layout>(
        &self,
        layout: &'layout IndexedLayout<'data>,
    ) -> Result<ElfSection64<'data, 'layout, LittleEndian>> {
        layout.get_elf_section(self.input_section_id)
    }

    /// Check that the section addresses are all the same as what we found previously. Otherwise,
    /// report an error.
    fn verify_consistent(
        &self,
        addresses_by_binary: &[u64],
        symbol_name: &[u8],
        binaries: &[Binary<'_>],
        layout: &IndexedLayout,
    ) -> Result {
        for (file_number, (&a, &b)) in self
            .addresses_by_binary
            .iter()
            .zip(addresses_by_binary)
            .enumerate()
        {
            if a != b {
                bail!(
                    "Symbols `{existing_sym}` and `{new_sym}` in `{name}` yield \
                        inconsistent addresses for section `{section_name}` in {input_file}: \
                        0x{a:x?} vs 0x{b:x?}",
                    input_file = layout.input_file_for_section(self.input_section_id),
                    existing_sym = String::from_utf8_lossy(self.found_via_symbol),
                    new_sym = String::from_utf8_lossy(symbol_name),
                    section_name = layout.get_elf_section(self.input_section_id)?.name()?,
                    name = &binaries[file_number],
                );
            }
        }

        Ok(())
    }
}

pub(crate) fn validate_indexes(bin: &Binary) -> Result {
    if let Some(error) = &bin.address_index.index_error {
        bail!("{error}");
    }
    Ok(())
}

pub(crate) fn validate_got_plt(bin: &Binary) -> Result {
    let Some(dynamic) = bin.address_index.dynamic_segment_address else {
        return Ok(());
    };
    let got_plt_sec = bin
        .section_by_name(GOT_PLT_SECTION_NAME_STR)
        .context(".got.plt missing")?;
    let got_plt: &[u64] = object::slice_from_all_bytes(got_plt_sec.data()?)
        .map_err(|_| anyhow!("Invalid .got.plt"))?;
    if got_plt.len() < 3 {
        bail!(".got.plt is too short");
    }
    if got_plt[0] != dynamic {
        bail!("First entry of .got.plt should point to .dynamic");
    }
    if got_plt[1] != 0 || got_plt[2] != 0 {
        bail!(".got.plt[1] and .got.plt[2] are reserved and should be zero");
    }

    Ok(())
}

const ORIG: &str = "ORIG";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SymtabEntryInfo<'data> {
    name: SymbolName<'data>,
    is_weak: bool,
    visibility: Visibility,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct SymbolName<'data> {
    bytes: &'data [u8],
    version: Option<&'data [u8]>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Visibility {
    Default,
    Protected,
    Hidden,
    Other(u8),
}

#[derive(Clone, Copy)]
enum Data<'data> {
    Bytes(&'data [u8]),
    Bss,
}

impl std::fmt::Debug for SymbolName<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", String::from_utf8_lossy(self.bytes))?;
        if let Some(version) = self.version {
            write!(f, "@{}", String::from_utf8_lossy(version))?;
        }
        Ok(())
    }
}

pub(crate) struct AddressIndex<'data> {
    plt_indexes: Vec<PltIndex<'data>>,
    got_tables: Vec<GotIndex<'data>>,
    index_error: Option<anyhow::Error>,
    jmprel_address: Option<u64>,
    versym_address: Option<u64>,
    dynamic_segment_address: Option<u64>,
    dynamic_relocations_by_address: HashMap<u64, object::Relocation>,
    dynamic_relocations_by_symbol_index: HashMap<object::SymbolIndex, Vec<object::Relocation>>,
    tls_segment_size: u64,

    /// GOT addresses for each JMPREL relocation by their index.
    jmprel_got_addresses: Vec<u64>,

    /// The address of the start of the .got section.
    got_base_address: Option<u64>,

    /// Version names by their index.
    verdef: Vec<Option<&'data [u8]>>,
    verneed: Vec<Option<&'data [u8]>>,

    /// Dynamic symbol names by their index.
    dynamic_symbols: Vec<SymtabEntryInfo<'data>>,
    bin_attributes: BinAttributes,

    symbols_by_address: HashMap<u64, Vec<object::SymbolIndex>>,
}

struct PltIndex<'data> {
    plt_base: u64,
    entry_length: u64,
    bytes: &'data [u8],
}

impl PltIndex<'_> {
    /// Returns the address of the GOT entry for the specified PLT address or None if the supplied
    /// address isn't a valid PLT entry in this index.
    fn lookup_got_address<A: Arch>(
        &self,
        plt_address: u64,
        index: &AddressIndex,
    ) -> Result<Option<u64>> {
        if !(self.plt_base..self.plt_base + self.bytes.len() as u64).contains(&plt_address) {
            return Ok(None);
        }

        let offset = plt_address - self.plt_base;

        if self.entry_length != 0 && !offset.is_multiple_of(self.entry_length) {
            bail!(
                "PLT address 0x{plt_address:x} is not aligned to 0x{:x}",
                self.entry_length
            );
        }

        let plt_entry = if self.entry_length == 0 {
            // Sometimes linkers don't set the entry size on PLT sections. In that case, we try both
            // size 8 and if that fails, try size 16.
            self.decode_plt_entry_with_size::<A>(offset, 8)
                .or_else(|| self.decode_plt_entry_with_size::<A>(offset, 16))
        } else {
            self.decode_plt_entry_with_size::<A>(offset, self.entry_length)
        }
        .with_context(|| format!("Unrecognised PLT entry format at 0x{plt_address:x}"))?;

        let got_address = match plt_entry {
            PltEntry::DerefJmp(address) => address,
            PltEntry::JumpSlot(slot_index) => index
                .jmprel_got_addresses
                .get(slot_index as usize)
                .copied()
                .with_context(|| {
                    format!(
                        "Invalid jump slot index {slot_index} out of {}",
                        index.jmprel_got_addresses.len()
                    )
                })?,
        };

        Ok(Some(got_address))
    }

    fn decode_plt_entry_with_size<A: Arch>(
        &self,
        offset: u64,
        entry_size: u64,
    ) -> Option<PltEntry> {
        let entry_bytes = &self.bytes[offset as usize..(offset + entry_size) as usize];
        A::decode_plt_entry(entry_bytes, self.plt_base, offset)
    }
}

impl<'data> AddressIndex<'data> {
    pub(crate) fn new(elf_file: &'data ElfFile64<'data>) -> Self {
        let mut info = Self {
            index_error: None,
            jmprel_address: None,
            versym_address: None,
            dynamic_segment_address: None,
            got_base_address: None,
            tls_segment_size: get_tls_segment_size(elf_file),
            plt_indexes: Default::default(),
            got_tables: Default::default(),
            verdef: Default::default(),
            verneed: Default::default(),
            dynamic_symbols: Default::default(),
            jmprel_got_addresses: Vec::new(),
            dynamic_relocations_by_address: Default::default(),
            bin_attributes: BinAttributes {
                // These may be overridden in `index_dynamic`.
                output_kind: if elf_file.kind() == ObjectKind::Executable {
                    OutputKind::Executable
                } else {
                    OutputKind::SharedObject
                },
                relocatability: Relocatability::NonRelocatable,
                link_type: LinkType::Static,
            },
            dynamic_relocations_by_symbol_index: Default::default(),
            symbols_by_address: index_symbols_by_address(elf_file),
        };

        if let Err(error) = info.build_indexes(elf_file) {
            info.index_error = Some(error);
        }
        info
    }

    fn build_indexes(&mut self, elf_file: &ElfFile64<'data>) -> Result {
        self.index_dynamic(elf_file);
        self.verdef = Self::index_verdef(elf_file)?;
        self.verneed = Self::index_verneed(elf_file)?;
        self.dynamic_symbols = self.index_dynamic_symbols(elf_file)?;
        self.index_got_tables(elf_file).unwrap();
        self.index_relocations(elf_file);
        self.index_plt_sections(elf_file)?;
        Ok(())
    }

    fn index_verdef(elf_file: &ElfFile64<'data>) -> Result<Vec<Option<&'data [u8]>>> {
        let e = LittleEndian;
        let mut versions = Vec::new();

        let maybe_verdef = elf_file
            .sections()
            .find_map(|section| {
                section
                    .elf_section_header()
                    .gnu_verdef(e, elf_file.data())
                    .transpose()
            })
            .transpose()?;

        let Some((mut verdef_iterator, strings_index)) = maybe_verdef else {
            return Ok(versions);
        };

        let strings = elf_file
            .elf_section_table()
            .strings(e, elf_file.data(), strings_index)?;

        while let Some((_verdef, mut aux_iterator)) = verdef_iterator.next()? {
            // We don't need verdef parent here, so take only the first entry
            if let Some(aux) = aux_iterator.next()? {
                let name = aux.name(e, strings)?;
                versions.push(Some(name));
            }
        }

        Ok(versions)
    }

    fn index_verneed(elf_file: &ElfFile64<'data>) -> Result<Vec<Option<&'data [u8]>>> {
        let e = LittleEndian;
        let mut versions = Vec::new();

        let maybe_verneed = elf_file
            .sections()
            .find_map(|section| {
                section
                    .elf_section_header()
                    .gnu_verneed(e, elf_file.data())
                    .transpose()
            })
            .transpose()?;

        let Some((mut verneed_iterator, strings_index)) = maybe_verneed else {
            return Ok(versions);
        };

        let strings = elf_file
            .elf_section_table()
            .strings(e, elf_file.data(), strings_index)?;

        while let Some((_verneed, mut aux_iterator)) = verneed_iterator.next()? {
            while let Some(aux) = aux_iterator.next()? {
                let name = aux.name(e, strings)?;
                let index = aux.vna_other.get(e) as usize;
                if index >= versions.len() {
                    versions.resize(index + 1, None);
                }
                versions[index] = Some(name);
            }
        }

        Ok(versions)
    }

    fn index_dynamic_symbols(
        &self,
        elf_file: &ElfFile64<'data>,
    ) -> Result<Vec<SymtabEntryInfo<'data>>> {
        let symbol_version_indexes: Option<&[u16]> = self
            .versym_address
            .and_then(|address| {
                elf_file
                    .sections()
                    .find(|section| section.address() == address)
            })
            .and_then(|section| section.data().ok())
            .and_then(|data| object::slice_from_all_bytes(data).ok());

        let mut dynamic_symbol_names = Vec::new();
        let mut max_index = 0;

        for sym in elf_file.dynamic_symbols() {
            let sym_index = sym.index().0;
            max_index = max_index.max(sym_index);
            let version_index = symbol_version_indexes
                .and_then(|indexes| indexes.get(sym_index))
                .copied();

            let version: Option<&[u8]> = match version_index {
                Some(object::elf::VER_NDX_LOCAL) | Some(object::elf::VER_NDX_GLOBAL)
                    if !sym.is_definition() =>
                {
                    // Unversioned, undefined symbols are sometimes emitted as VER_NDX_GLOBAL (LLD
                    // and pre-2025 GNU ld) and sometimes as VER_NDX_LOCAL (GNU ld from late 2025).
                    // The spec doesn't say which they should be, so for undefined symbols, we don't
                    // differentiate between local and global.
                    Some(b"*unversioned*")
                }
                Some(object::elf::VER_NDX_LOCAL) => Some(b"*local*"),
                Some(object::elf::VER_NDX_GLOBAL) => Some(b"*global*"),
                Some(version_index) if version_index > object::elf::VER_NDX_GLOBAL => self
                    .verdef
                    .get(version_index as usize - 1)
                    .or_else(|| self.verneed.get(version_index as usize))
                    .copied()
                    .flatten(),
                _ => None,
            };

            let name_bytes = sym.name_bytes()?;
            let name = SymbolName {
                bytes: name_bytes,
                version,
            };

            let visibility = Visibility::from_sym(sym.elf_symbol());

            ensure!(
                visibility != Visibility::Hidden,
                "Dynamic symbol {name} has unexpected hidden visibility"
            );

            while dynamic_symbol_names.len() < sym_index {
                dynamic_symbol_names.push(SymtabEntryInfo {
                    name: SymbolName {
                        bytes: &[],
                        version: None,
                    },
                    is_weak: false,
                    visibility: Visibility::Default,
                });
            }

            dynamic_symbol_names.push(SymtabEntryInfo {
                name,
                is_weak: sym.is_weak(),
                visibility,
            });
        }

        if let Some(versym) = symbol_version_indexes {
            let versym_len = versym.len();
            let num_symbols = max_index + 1;
            if versym_len != num_symbols {
                bail!(".gnu.version contains {versym_len}, but .dynsym contains {num_symbols}");
            }
        }

        Ok(dynamic_symbol_names)
    }

    fn index_relocations(&mut self, elf_file: &ElfFile64<'data>) {
        if let Some(dynamic_relocations) = elf_file.dynamic_relocations() {
            for (_, rel) in dynamic_relocations {
                if let RelocationTarget::Symbol(symbol_index) = rel.target() {
                    self.dynamic_relocations_by_symbol_index
                        .entry(symbol_index)
                        .or_default()
                        .push(rel);
                }
            }
        }

        if let Some(dynamic_relocations) = elf_file.dynamic_relocations() {
            self.dynamic_relocations_by_address
                .extend(dynamic_relocations);
        }

        for section in elf_file.sections() {
            self.dynamic_relocations_by_address
                .extend(section.relocations());
        }
    }

    fn index_plt_sections(&mut self, elf_file: &ElfFile64<'data>) -> Result {
        self.index_plt_named(elf_file, PLT_SECTION_NAME_STR)?;
        self.index_plt_named(elf_file, PLT_SEC_SECTION_NAME_STR)?;
        self.index_plt_named(elf_file, PLT_GOT_SECTION_NAME_STR)?;
        self.index_plt_named(elf_file, IPLT_SECTION_NAME_STR)?;
        Ok(())
    }

    fn index_plt_named(&mut self, elf_file: &ElfFile64<'data>, section_name: &str) -> Result {
        let Some(section) = elf_file.section_by_name(section_name) else {
            return Ok(());
        };

        let Ok(bytes) = section.data() else {
            return Ok(());
        };

        let entry_length = section.elf_section_header().sh_entsize(LittleEndian) as usize;

        if ![0, 8, 0x10].contains(&entry_length) {
            bail!("{section_name} has unrecognised entry length {entry_length}");
        }

        let plt_base = section.address();

        self.plt_indexes.push(PltIndex {
            bytes,
            plt_base,
            entry_length: entry_length as u64,
        });

        Ok(())
    }

    fn index_got_tables(&mut self, elf_file: &ElfFile64<'data>) -> Result {
        self.got_tables = [GOT_PLT_SECTION_NAME_STR, GOT_SECTION_NAME_STR]
            .iter()
            .filter_map(|table_name| Self::index_got_table(elf_file, table_name).transpose())
            .try_collect()?;

        self.got_base_address = self.got_tables.first().map(|t| t.address_range.start);

        Ok(())
    }

    fn index_got_table(
        elf_file: &ElfFile64<'data>,
        table_name: &str,
    ) -> Result<Option<GotIndex<'data>>> {
        let Some(got_section) = elf_file.section_by_name(table_name) else {
            return Ok(None);
        };

        let data = got_section.data()?;
        let raw_entries: &[u64] = if data.is_empty() {
            // An empty .got may not be aligned, so we avoid calling object::slice_from_bytes.
            &[]
        } else {
            let entry_size = size_of::<u64>();
            object::slice_from_bytes(data, data.len() / entry_size)
                .unwrap()
                .0
        };

        let base = got_section.address();
        Ok(Some(GotIndex {
            address_range: base..base + data.len() as u64,
            entries: raw_entries,
        }))
    }

    fn index_dynamic(&mut self, elf_file: &ElfFile64) {
        let e = LittleEndian;

        let dynamic_segment = elf_file
            .elf_program_headers()
            .iter()
            .find(|seg| seg.p_type(LittleEndian) == object::elf::PT_DYNAMIC);

        self.dynamic_segment_address = dynamic_segment.map(|seg| seg.p_vaddr(e));

        if elf_file.elf_header().e_type(LittleEndian) == object::elf::ET_DYN {
            self.bin_attributes.relocatability = Relocatability::Relocatable;
        }

        if dynamic_segment.is_none() {
            self.bin_attributes.output_kind = OutputKind::Executable;
        };

        dynamic_segment
            .and_then(|seg| seg.data(LittleEndian, elf_file.data()).ok())
            .and_then(|dynamic_table_data| {
                object::slice_from_all_bytes::<object::elf::Dyn64<LittleEndian>>(dynamic_table_data)
                    .ok()
            })
            .unwrap_or_default()
            .iter()
            .for_each(|entry| match entry.d_tag.get(e) as u32 {
                object::elf::DT_JMPREL => {
                    self.jmprel_address = Some(entry.d_val.get(e));
                }
                object::elf::DT_VERSYM => {
                    self.versym_address = Some(entry.d_val.get(e));
                }
                object::elf::DT_FLAGS_1 => {
                    if entry.d_val.get(e) & u64::from(object::elf::DF_1_PIE) != 0 {
                        self.bin_attributes.output_kind = OutputKind::Executable;
                    }
                }
                object::elf::DT_NEEDED => {
                    self.bin_attributes.link_type = LinkType::Dynamic;
                }
                _ => {}
            });
    }

    fn plt_to_got_address<A: Arch>(&self, plt_address: u64) -> Result<Option<u64>> {
        self.plt_indexes
            .iter()
            .find_map(|index| index.lookup_got_address::<A>(plt_address, self).transpose())
            .transpose()
    }

    fn is_got_address(&self, address: u64) -> bool {
        self.got_tables
            .iter()
            .any(|t| t.address_range.contains(&address))
    }

    pub(crate) fn symbols_at_address(&self, address: u64) -> &[object::SymbolIndex] {
        self.symbols_by_address
            .get(&address)
            .map(|s| s.as_slice())
            .unwrap_or_default()
    }

    pub(crate) fn relocation_at_address(&self, address: u64) -> Option<&object::Relocation> {
        self.dynamic_relocations_by_address.get(&address)
    }

    fn dereference_got_address<R: RType>(
        &self,
        got_address: u64,
        relocation_kind: RelocationKind,
        bin: &Binary<'data>,
        expected_value_kind: BasicValueKind,
    ) -> Result<Referent<'data, R>> {
        let table = self
            .got_tables
            .iter()
            .find(|table| table.address_range.contains(&got_address))
            .context("Address isn't in any GOT tables")?;

        table.dereference_got_address(got_address, relocation_kind, bin, expected_value_kind)
    }

    fn is_relocatable(&self) -> bool {
        self.bin_attributes.relocatability == Relocatability::Relocatable
    }
}

fn get_tls_segment_size(elf_file: &ElfFile64) -> u64 {
    elf_file
        .elf_program_headers()
        .iter()
        .find_map(|header| {
            (header.p_type(LittleEndian) == object::elf::PT_TLS)
                .then(|| header.p_memsz(LittleEndian))
        })
        .unwrap_or(0)
}

fn index_symbols_by_address(elf_file: &ElfFile64) -> HashMap<u64, Vec<object::SymbolIndex>> {
    let mut out: HashMap<u64, Vec<object::SymbolIndex>> = HashMap::new();

    for sym in elf_file.symbols() {
        out.entry(sym.address()).or_default().push(sym.index());
    }

    out
}

struct GotIndex<'data> {
    /// The addresses covered by this table.
    address_range: Range<u64>,

    entries: &'data [u64],
}

impl<'data> GotIndex<'data> {
    fn dereference_got_address<R: RType>(
        &self,
        got_address: u64,
        relocation_kind: RelocationKind,
        bin: &Binary<'data>,
        expected_value_kind: BasicValueKind,
    ) -> Result<Referent<'data, R>> {
        let index = &bin.address_index;

        let offset = got_address
            .checked_sub(self.address_range.start)
            .context("got_address outside index range")?;

        let entry_size = size_of::<u64>() as u64;
        if !offset.is_multiple_of(entry_size) {
            bail!("Unaligned reference to GOT 0x{got_address:x}");
        }

        if let Some(rel) = index.dynamic_relocations_by_address.get(&got_address) {
            let r_type = get_r_type::<R>(rel);

            let dynamic_relocation_kind = r_type
                .dynamic_relocation_kind()
                .with_context(|| format!("Unsupported dynamic relocation {r_type}"))?;

            let symbol = if let object::RelocationTarget::Symbol(symbol_index) = rel.target() {
                Some(
                    index
                        .dynamic_symbols
                        .get(symbol_index.0)
                        .context("Symbol index out of range")?,
                )
            } else {
                None
            };

            match dynamic_relocation_kind {
                DynamicRelocationKind::Relative => {
                    Ok(Referent::UnmatchedAddress(UnmatchedAddress {
                        address: rel.addend() as u64,
                        ..Default::default()
                    }))
                }
                DynamicRelocationKind::Irelative => Ok(Referent::IFunc(determine_ifunc_name(
                    rel.addend() as u64,
                    bin,
                ))),
                DynamicRelocationKind::DtpMod => {
                    match (expected_value_kind, symbol) {
                        (BasicValueKind::TlsModuleId, None) => Ok(Referent::TlsModuleId),
                        (BasicValueKind::TlsModuleId, Some(symbol)) => {
                            bail!("Expected TLSLD, but found DTPMOD with symbol (`{symbol}`)");
                        }
                        (BasicValueKind::TlsGd, Some(symbol)) => Ok(Referent::TlsGd(*symbol)),
                        (BasicValueKind::TlsGd, None) => {
                            // There's no symbol associated with the DTPMOD relocation, so it's a
                            // TLS variable within the current DSO. Read
                            // the next word of data to get the offset.
                            let tls_offset =
                                read_word_at(bin.elf_file, got_address + size_of::<u64>() as u64)?
                                    .context("Short read after DTPMOD")?
                                    as i64;
                            Ok(Referent::UnmatchedTlsOffset(tls_offset))
                        }
                        (other, _) => bail!("Unexpected DTPMOD when looking for {other:?}"),
                    }
                }
                DynamicRelocationKind::TpOff if symbol.is_none() => {
                    Ok(Referent::UnmatchedTlsOffset(rel.addend()))
                }
                DynamicRelocationKind::TlsDesc => {
                    if let Some(symbol) = symbol {
                        Ok(Referent::TlsDesc(*symbol))
                    } else {
                        Ok(Referent::UnmatchedTlsOffset(rel.addend()))
                    }
                }
                _ => {
                    let symbol = symbol.with_context(|| format!("{r_type} without symbol"))?;

                    Ok(Referent::DynamicRelocation(DynamicRelocation {
                        entry: *symbol,
                        r_type,
                        addend: rel.addend(),
                    }))
                }
            }
        } else {
            // No dynamic relocation, just read from the original file data.
            let raw_value = *self
                .entries
                .get((offset / entry_size) as usize)
                .context("got_address past end of index range")?;

            match relocation_kind {
                RelocationKind::GotTpOff
                | RelocationKind::GotTpOffLoongArch64
                | RelocationKind::GotTpOffGot
                | RelocationKind::GotTpOffGotBase => {
                    Ok(Referent::UnmatchedTlsOffset(raw_value as i64))
                }
                RelocationKind::TlsDescCall => Ok(Referent::TlsDescCall),
                RelocationKind::Absolute
                | RelocationKind::AbsoluteLowPart
                | RelocationKind::AbsoluteSet
                | RelocationKind::AbsoluteSetWord6
                | RelocationKind::AbsoluteAddition
                | RelocationKind::AbsoluteAdditionWord6
                | RelocationKind::AbsoluteSubtraction
                | RelocationKind::AbsoluteSubtractionWord6
                | RelocationKind::Relative
                | RelocationKind::RelativeRiscVLow12
                | RelocationKind::RelativeLoongArchHigh
                | RelocationKind::SymRelGotBase
                | RelocationKind::GotRelGotBase
                | RelocationKind::Got
                | RelocationKind::PltRelGotBase
                | RelocationKind::PltRelative
                | RelocationKind::GotRelative
                | RelocationKind::GotRelativeLoongArch64
                | RelocationKind::None
                | RelocationKind::PairSubtractionULEB128(..)
                | RelocationKind::Alignment => Ok(Referent::Absolute(raw_value)),
                RelocationKind::TlsGd
                | RelocationKind::TlsGdGot
                | RelocationKind::TlsGdGotBase
                | RelocationKind::TlsLd
                | RelocationKind::TlsLdGot
                | RelocationKind::TlsLdGotBase
                | RelocationKind::DtpOff
                | RelocationKind::TpOff
                | RelocationKind::TlsDesc
                | RelocationKind::TlsDescLoongArch64
                | RelocationKind::TlsDescGot
                | RelocationKind::TlsDescGotBase => {
                    bail!("Missing dynamic relocation for {relocation_kind:?}")
                }
            }
        }
    }
}

/// Returns the name of the ifunc resolver given the resolver address. We choose to return the name
/// of the resolver rather than the ifunc name because GNU ld and lld are inconsistent with where
/// they point the symbol for the ifunc, whereas the resolver's symbol consistently points at the
/// address of the resolver.
fn determine_ifunc_name<'data>(address: u64, bin: &Binary<'data>) -> Option<SymbolName<'data>> {
    bin.address_index
        .symbols_at_address(address)
        .iter()
        .filter_map(|symbol_index| {
            let symbol = bin.elf_file.symbol_by_index(*symbol_index).ok()?;

            // We're likely to get symbols of type STT_GNU_IFUNC. The resolver should be just a
            // regular function and that's what we want.
            if symbol.elf_symbol().st_type() != object::elf::STT_FUNC {
                return None;
            }

            Some(SymbolName {
                bytes: symbol.name_bytes().ok()?,
                version: None,
            })
        })
        .max()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct DynamicRelocation<'data, R: RType> {
    entry: SymtabEntryInfo<'data>,
    r_type: R,
    addend: i64,
}

/// Attempts to read some data starting at `address` up to the end of the segment.
fn read_segment<'data>(elf_file: &ElfFile64<'data>, address: u64) -> Result<Option<Data<'data>>> {
    // This could well end up needing to be optimised if we end up caring about performance.
    for (seg_index, raw_seg) in elf_file.elf_program_headers().iter().enumerate() {
        let e = LittleEndian;
        if raw_seg.p_type(e) != object::elf::PT_LOAD {
            continue;
        }
        let seg_address = raw_seg.p_paddr(e);
        let seg_len = raw_seg.p_memsz(e);
        let seg_end = seg_address + seg_len;

        if seg_address <= address && address < seg_end {
            let start = (address - seg_address) as usize;
            let file_start = raw_seg.p_offset(e) as usize;
            let file_size = raw_seg.p_filesz(e) as usize;
            let file_end = file_start + file_size;
            let file_bytes = elf_file.data();
            if file_bytes.is_empty() {
                return Ok(Some(Data::Bss));
            }
            let bytes = &file_bytes
                .get(file_start + start..file_end)
                .with_context(|| format!("Invalid ELF segment {seg_index}"))?;
            return Ok(Some(Data::Bytes(bytes)));
        }
    }
    Ok(None)
}

fn read_word_at(elf_file: &ElfFile64, address: u64) -> Result<Option<u64>> {
    let Some(bytes) = read_bytes(elf_file, address, size_of::<u64>() as u64)? else {
        return Ok(None);
    };
    let Some(chunk) = bytes.first_chunk() else {
        return Ok(None);
    };
    Ok(Some(u64::from_le_bytes(*chunk)))
}

fn read_bytes<'data>(
    elf_file: &ElfFile64<'data>,
    address: u64,
    len: u64,
) -> Result<Option<&'data [u8]>> {
    Ok(
        read_segment(elf_file, address)?.and_then(|data| match data {
            Data::Bytes(bytes) => bytes.get(..len as usize),
            Data::Bss => None,
        }),
    )
}

/// Returns bytes starting at `address` up to the end of the containing segment. This is useful when
/// you don't know what length you need to read, e.g. when reading a null-terminated string.
fn read_bytes_starting_at<'data>(
    elf_file: &ElfFile64<'data>,
    address: u64,
) -> Result<Option<&'data [u8]>> {
    Ok(
        read_segment(elf_file, address)?.and_then(|data| match data {
            Data::Bytes(bytes) => Some(bytes),
            Data::Bss => None,
        }),
    )
}

impl Display for SymbolName<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            symbolic_demangle::demangle(&String::from_utf8_lossy(self.bytes))
        )?;
        if let Some(version) = self.version {
            write!(f, "@{}", String::from_utf8_lossy(version))?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
struct BinAttributes {
    output_kind: OutputKind,
    relocatability: Relocatability,
    link_type: LinkType,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputKind {
    Executable,
    SharedObject,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Relocatability {
    Relocatable,
    NonRelocatable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinkType {
    Dynamic,
    Static,
}

impl BinAttributes {
    fn type_name(self) -> &'static str {
        match (self.output_kind, self.relocatability, self.link_type) {
            (OutputKind::Executable, Relocatability::Relocatable, LinkType::Dynamic) => {
                "dynamic-pie"
            }
            (OutputKind::Executable, Relocatability::Relocatable, LinkType::Static) => "static-pie",
            (OutputKind::Executable, Relocatability::NonRelocatable, LinkType::Dynamic) => {
                "dynamic-non-pie"
            }
            (OutputKind::Executable, Relocatability::NonRelocatable, LinkType::Static) => {
                "static-non-pie"
            }
            (OutputKind::SharedObject, Relocatability::Relocatable, LinkType::Dynamic) => {
                "shared-object"
            }
            (OutputKind::SharedObject, _, _) => "invalid-shared-object",
        }
    }
}

fn relocation_num_bytes(info: RelocationKindInfo) -> usize {
    match info.size {
        linker_utils::elf::RelocationSize::ByteSize(b) => b,
        linker_utils::elf::RelocationSize::BitMasking(mask) => {
            (mask.range.end.div_ceil(8) - mask.range.start / 8) as usize
        }
    }
}

fn read_value(size: RelocationSize, value_bytes: &[u8]) -> Result<u64> {
    match size {
        RelocationSize::ByteSize(8) => Ok(u64::from_le_bytes(
            *value_bytes
                .first_chunk::<8>()
                .context("Invalid relocation offset")?,
        )),
        RelocationSize::ByteSize(4) => Ok(u64::from(u32_from_slice(value_bytes))),
        RelocationSize::ByteSize(0) => Ok(0),
        RelocationSize::ByteSize(other) => bail!("Unsupported relocation size {other}"),
        RelocationSize::BitMasking(BitMask {
            range,
            instruction: insn,
        }) => {
            let (raw_value, _negative) = insn.read_value(value_bytes);
            Ok(raw_value << range.start)
        }
    }
}

impl<A: Arch> Relaxation<A> {
    fn relocation_size(&self) -> Result<RelocationSize> {
        let size = self.new_r_type.relocation_info()?.size;

        if let Some(alt_r_type) = self.alt_r_type {
            let alt_size = alt_r_type.relocation_info()?.size;
            assert_eq!(alt_size, size);
        }

        Ok(size)
    }

    fn relocation_num_bytes(&self) -> Result<usize> {
        let relocation_info = self.new_r_type.relocation_info()?;

        Ok(relocation_num_bytes(relocation_info))
    }
}

fn has_copy_relocation_for_symbol_named<R: RType>(symbol_name: &[u8], bin: &Binary) -> bool {
    bin.name_index
        .dynamic_by_name
        .get(symbol_name)
        .is_some_and(|symbol_indexes| {
            symbol_indexes.iter().any(|symbol_index| {
                bin.address_index
                    .dynamic_relocations_by_symbol_index
                    .get(symbol_index)
                    .is_some_and(|relocations| {
                        relocations.iter().any(|rel| {
                            let r_type = get_r_type::<R>(rel);
                            r_type.dynamic_relocation_kind() == Some(DynamicRelocationKind::Copy)
                        })
                    })
            })
        })
}

fn populate_section_coverage(cov: &mut crate::Coverage, layout: &IndexedLayout<'_>) {
    layout.all_sections_do(|section_info| {
        let Ok(elf_section) = layout.get_elf_section(section_info.section_id) else {
            return;
        };

        let Some(name) = elf_section.name_bytes().ok() else {
            return;
        };

        cov.sections.insert(
            section_info.section_id,
            SectionCoverage {
                original_file: layout
                    .input_file_for_section(section_info.section_id)
                    .identifier
                    .to_owned(),
                name: String::from_utf8_lossy(name).into_owned(),
                num_bytes: elf_section.size(),
                diffed: false,
            },
        );
    });
}

impl Display for SymtabEntryInfo<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.name, f)?;
        if self.is_weak {
            write!(f, " (weak)")?;
        }

        match self.visibility {
            Visibility::Default => {}
            Visibility::Protected => write!(f, " (protected)")?,
            Visibility::Hidden => write!(f, " (hidden)")?,
            Visibility::Other(other) => write!(f, " (vis={other})")?,
        }
        Ok(())
    }
}

impl Display for OutputKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutputKind::Executable => write!(f, "executable"),
            OutputKind::SharedObject => write!(f, "shared-object"),
        }
    }
}

impl Visibility {
    fn from_sym(elf_symbol: &object::elf::Sym64<LittleEndian>) -> Visibility {
        match elf_symbol.st_visibility() {
            object::elf::STV_DEFAULT => Visibility::Default,
            object::elf::STV_PROTECTED => Visibility::Protected,
            object::elf::STV_HIDDEN => Visibility::Hidden,
            other => Visibility::Other(other),
        }
    }
}