qld 0.1.0

A fast, parallel linker compatible with GNU ld, gold, lld and mold
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
//! Per-architecture relocation handling.
//!
//! Each architecture module classifies relocation types, rewrites relaxable
//! instruction sequences and writes linker-generated stubs. The rest of the
//! ELF backend never names a relocation constant: it asks [`Arch`], which is
//! chosen once per link ([`Arch::of`]) and dispatches to the module for
//! x86-64 (and x32), AArch64, RISC-V (RV64 and RV32), LoongArch64,
//! PowerPC64, i386 or s390x.
//!
//! The vocabulary is shared, so the relocation scan and the writer run one
//! loop for every architecture:
//!
//! - [`Kind`] says what a relocation computes (`S + A`, `Page(S + A) -
//!   Page(P)`, a GOT slot's address, a thread pointer offset, …) and
//!   [`GotKind`] which GOT entry it goes through;
//! - [`Width`] says how the result is stored: a data field (in the
//!   output's byte order, [`write_value_as`]), or an AArch64, RISC-V,
//!   LoongArch, PowerPC64 or s390x instruction field
//!   ([`crate::arch::aarch64::Field`], [`crate::arch::riscv::Field`],
//!   [`crate::arch::loongarch::Field`], [`crate::arch::ppc64::Field`],
//!   [`crate::arch::s390x::Field`]);
//! - [`DynKind`] names the dynamic relocation a GOT slot, a PLT slot or a
//!   copy needs, without naming its number.

pub mod aarch64;
pub mod aarch64_errata;
pub mod arm;
pub mod i386;
pub mod loongarch;
pub mod ppc64;
pub mod riscv;
pub mod s390x;
pub mod shrink;
pub mod thunk;
pub mod x86_64;

use crate::args::LinkOptions;
use crate::elf::read::Relocation;
use crate::elf::read::consts::{
    EM_AARCH64, EM_LOONGARCH, EM_PPC64, EM_RISCV, EM_X86_64, SHF_EXECINSTR, reloc_name,
};
use crate::target::{Architecture, Target};

/// The architecture an ELF link targets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Arch {
    /// x86-64.
    #[default]
    X86_64,
    /// AArch64 (LP64, little-endian).
    AArch64,
    /// RISC-V 64 (LP64, little-endian).
    RiscV64,
    /// LoongArch64 (LP64D, little-endian).
    LoongArch64,
    /// PowerPC64, little-endian, ELFv2 ABI.
    Ppc64,
    /// s390x (z/Architecture, 64-bit, big-endian).
    S390x,
    /// i386 (32-bit x86).
    ///
    /// The ELF32 architectures are last, so that the checks for them are
    /// one comparison ([`Arch::is_word`], [`Arch::kind`]).
    I386,
    /// x32: x86-64 with 32-bit pointers (ILP32), in ELF32 objects.
    X32,
    /// RISC-V 32 (ILP32, little-endian): the RV64 code with 4-byte words.
    RiscV32,
    /// 32-bit Arm (ARMv7-A, little-endian, EABI).
    Arm,
}

/// What a relocation computes.
///
/// `S` is the symbol's address, `A` the addend, `P` the place being
/// relocated, `G` the address of the symbol's GOT entry (of the
/// relocation's [`GotKind`]), `GOT` the GOT base, `TP` the thread pointer
/// and `Page(x)` the address with its low 12 bits cleared.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    /// Nothing to do.
    None,
    /// `S + A`.
    Abs,
    /// `S + A - P`.
    Pc,
    /// `Page(S + A) - Page(P)`.
    Page,
    /// `G + A - P`.
    Got,
    /// `Page(G + A) - Page(P)`.
    GotPage,
    /// `G + A`.
    GotAbs,
    /// `G + A - Page(GOT)`.
    GotPageOff,
    /// `G + A - GOT`.
    GotSlotRel,
    /// A load through a GOT entry that is kept, which the architecture
    /// turns into a direct address computation once it knows the symbol's
    /// address ([`Arch::relax_got_load`]; s390x: `lgrl` and `lg` through
    /// `%r12` become `larl`). Otherwise `G + A - P` or `G + A - GOT`.
    GotRelax,
    /// `S + A - GOT`.
    GotRel,
    /// `GOT + A - P`.
    GotBasePc,
    /// `Z + A`, the symbol's size.
    Size,
    /// `S + A - TP`.
    TpOff,
    /// `S + A - TLS block start` in non-allocated sections, `S + A - TP` in
    /// allocated ones (local-dynamic code relaxed to local-exec).
    DtpOff,
    /// x86-64: a relaxed `GOTPCRELX`, `S + A - P` with the instruction
    /// rewritten.
    RelaxGotPc,
    /// x86-64: a relaxed `REX_GOTPCRELX` to an immediate operand, `S`; i386:
    /// a relaxed `GOT32X` load without a base register, `S + A`.
    RelaxGotPcNoPic,
    /// i386: a relaxed `GOT32X` load through a base register, turned into
    /// a `lea` of `S + A - GOT`.
    RelaxGotOff,
    /// General-dynamic → local-exec.
    GdToLe,
    /// Local-dynamic → local-exec.
    LdToLe,
    /// Initial-exec → local-exec.
    IeToLe,
    /// TLS descriptor → local-exec.
    DescToLe,
    /// A TLS descriptor call that becomes a no-op.
    DescCallToLe,
    /// General-dynamic → initial-exec.
    GdToIe,
    /// TLS descriptor → initial-exec.
    DescToIe,
    /// `S + A` added to the field's current contents (a label difference
    /// assembled as a pair of relocations: LoongArch `ADD*`).
    Add,
    /// `S + A` subtracted from the field's current contents (the other half
    /// of the pair: LoongArch `SUB*`).
    Sub,
    /// The low bits of `S + A` that complete a page-relative pair
    /// (LoongArch `pcalau12i` + `addi.d`): the same wherever the output is
    /// loaded, so it needs no dynamic relocation even in a PIE.
    PageOff,
    /// An instruction pair the architecture rewrites once it knows both
    /// `S + A` and the place ([`Arch::relax`]; LoongArch: a GOT load turned
    /// into an address computation, or linker relaxation to `pcaddi`).
    Relax,
    /// `A` alone: a hint whose addend locates a related instruction
    /// (PowerPC64 `R_PPC64_PCREL_OPT`).
    Addend,
}

/// What a GOT entry holds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GotKind {
    /// The symbol's address (one word).
    #[default]
    Address,
    /// TLS module ID and offset (two words).
    TlsGd,
    /// The thread pointer offset (one word).
    TpOff,
    /// A TLS descriptor (two words).
    TlsDesc,
    /// The module-local TLS module ID and a zero offset (two words).
    TlsLd,
}

/// How the computed value is stored.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Width {
    /// Nothing is written.
    None,
    /// 8 bytes.
    W64,
    /// 4 bytes, zero-extended by the processor.
    U32,
    /// 4 bytes, sign-extended.
    I32,
    /// 4 bytes, signed or unsigned.
    Any32,
    /// 2 bytes, signed or unsigned.
    Any16,
    /// 2 bytes, signed.
    I16,
    /// 1 byte, signed or unsigned.
    Any8,
    /// 1 byte, signed.
    I8,
    /// An AArch64 instruction (or data) field.
    Field(crate::arch::aarch64::Field),
    /// A RISC-V instruction or data field, including the label arithmetic
    /// fields that combine with their contents.
    RiscV(crate::arch::riscv::Field),
    /// A LoongArch instruction (or data) field.
    LoongArch(crate::arch::loongarch::Field),
    /// A PowerPC64 instruction (or data) field.
    Ppc(crate::arch::ppc64::Field),
    /// An s390x instruction field.
    S390(crate::arch::s390x::Field),
    /// A 32-bit Arm or Thumb instruction field.
    Arm(crate::arch::arm::Field),
}

/// A classified relocation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Class {
    /// What to compute.
    pub kind: Kind,
    /// How to store it.
    pub width: Width,
    /// Which GOT entry the `Got*` kinds use.
    pub slot: GotKind,
    /// The relocation that follows is part of this one's sequence and must
    /// not be processed again (the call a TLS relaxation removes).
    pub skip_next: bool,
}

impl Class {
    /// A classification with no GOT entry and no skipped successor.
    #[must_use]
    pub const fn new(kind: Kind, width: Width) -> Self {
        Self {
            kind,
            width,
            slot: GotKind::Address,
            skip_next: false,
        }
    }

    /// The same classification through GOT entry `slot`.
    #[must_use]
    pub const fn through(mut self, slot: GotKind) -> Self {
        self.slot = slot;
        self
    }

    /// The same classification, consuming the relocation that follows.
    #[must_use]
    pub const fn skipping(mut self) -> Self {
        self.skip_next = true;
        self
    }

    /// Whether the relocation reads a GOT entry, and so needs one.
    #[must_use]
    pub fn needs_got(self) -> bool {
        matches!(
            self.kind,
            Kind::Got
                | Kind::GotPage
                | Kind::GotAbs
                | Kind::GotPageOff
                | Kind::GotSlotRel
                | Kind::GotRelax
        )
    }

    /// Whether the relocation uses the GOT base, so `_GLOBAL_OFFSET_TABLE_`
    /// must exist.
    #[must_use]
    pub fn uses_got_base(self) -> bool {
        matches!(
            self.kind,
            Kind::GotSlotRel | Kind::GotRel | Kind::GotBasePc | Kind::GotPageOff | Kind::GotRelax
        )
    }

    /// Whether the relocation is an initial-exec access through a GOT entry
    /// holding the thread pointer offset.
    #[must_use]
    pub fn needs_gottpoff(self) -> bool {
        matches!(self.kind, Kind::GdToIe | Kind::DescToIe)
            || (self.needs_got() && self.slot == GotKind::TpOff)
    }

    /// Whether the relocation is a TLS access.
    #[must_use]
    pub fn is_tls(self) -> bool {
        matches!(
            self.kind,
            Kind::TpOff
                | Kind::DtpOff
                | Kind::GdToLe
                | Kind::LdToLe
                | Kind::IeToLe
                | Kind::DescToLe
                | Kind::DescCallToLe
                | Kind::GdToIe
                | Kind::DescToIe
        ) || (self.needs_got() && self.slot != GotKind::Address)
    }
}

/// How TLS accesses to one variable are linked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TlsMode {
    /// The variable is in the executable being linked: relax to local-exec.
    LocalExec,
    /// An executable accessing a shared library's variable: relax
    /// general-dynamic and descriptors to initial-exec.
    InitialExec,
    /// A shared object: keep the dynamic models.
    Dynamic,
}

/// What [`Arch::classify`] needs to know besides the relocation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClassifyContext {
    /// GOT-indirect accesses may be rewritten into direct ones.
    pub relax_got: bool,
    /// The output is position-independent, so an address cannot become an
    /// immediate operand.
    pub pic: bool,
    /// How TLS accesses to the relocation's symbol are linked.
    pub tls: TlsMode,
    /// How local-dynamic accesses are linked: by the kind of output, not
    /// the variable.
    pub tls_ld: TlsMode,
    /// The relocated section holds code (`SHF_EXECINSTR`).
    pub code: bool,
}

impl ClassifyContext {
    /// The context of a static executable: everything relaxes.
    #[must_use]
    pub const fn static_exec(relax_got: bool) -> Self {
        Self {
            relax_got,
            pic: false,
            tls: TlsMode::LocalExec,
            tls_ld: TlsMode::LocalExec,
            code: false,
        }
    }
}

/// Why a relocation cannot be handled.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClassifyError {
    /// The type is unknown or not valid in a relocatable object.
    Unsupported,
    /// A TLS relaxation found an instruction it cannot rewrite.
    BadTlsInstruction,
}

/// Why a relocation could not be written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ApplyError {
    /// The value does not fit the field.
    Overflow,
    /// The field lies outside the section.
    OutOfBounds,
    /// A relaxation found an instruction it cannot rewrite.
    BadInstruction,
}

/// The role of a dynamic relocation, without naming its number.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DynKind {
    /// The load base is added to the addend.
    Relative,
    /// The load base is added and the result called to get the value.
    Irelative,
    /// A lazily bound PLT slot.
    JumpSlot,
    /// A GOT slot holding a symbol's address.
    GlobDat,
    /// A copy of a shared library's data.
    Copy,
    /// A 64-bit absolute address of a symbol.
    Abs64,
    /// The TLS module ID of a symbol's module.
    DtpMod,
    /// A symbol's offset in its module's TLS block.
    DtpOff,
    /// A symbol's offset from the thread pointer.
    TpOff,
    /// A TLS descriptor.
    TlsDesc,
}

/// The values a relaxation may need, all computed by the writer.
#[derive(Clone, Copy, Debug, Default)]
pub struct RelaxValues {
    /// `S + A - TP`, the thread pointer offset of the target.
    pub tpoff: i64,
    /// The address of the GOT entry the relaxed sequence reads, if it keeps
    /// one (initial-exec).
    pub got: u64,
    /// `G + A - P` for that entry.
    pub got_pc: i64,
    /// The place being relocated.
    pub place: u64,
    /// The GOT base, which i386 initial-exec code addresses the entry from.
    pub got_base: u64,
}

/// A direct branch, as range-extension thunk planning and the writer both
/// see it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Branch {
    /// The relocation type.
    pub r_type: u32,
    /// The address of the branch instruction.
    pub place: u64,
    /// The symbol's address plus addend, or the stub's when the branch
    /// goes through one.
    pub target: u64,
    /// The callee's `st_other` (0 when unknown).
    pub st_other: u8,
    /// The branch goes to a PLT or IFUNC stub.
    pub via_stub: bool,
    /// The GOT word that stub jumps through, for calls that need a stub of
    /// their own (PowerPC64 code without a TOC pointer).
    pub slot: Option<u64>,
}

/// Options that change the shape of PLT entries.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PltFlags {
    /// The PLT header starts with a landing pad: x86-64 `endbr64`, or
    /// AArch64 `bti c` because PLT entries reach the header through
    /// `br x17`.
    pub landing_pad: bool,
    /// PLT entries start with one too. On x86-64 that is IBT (and the
    /// jumps move to `.plt.sec`); on AArch64 it is an executable's BTI PLT,
    /// whose entries may be a function's canonical address and so the
    /// target of an indirect call (GNU ld gives a shared object's entries
    /// none).
    pub entry_landing_pad: bool,
    /// AArch64 `-z pac-plt`: entries authenticate the address they loaded
    /// (`autia1716`) before branching to it.
    pub authenticate: bool,
    /// The output is position-independent: i386 PLT entries address the
    /// GOT through `%ebx` rather than absolutely.
    pub pic: bool,
}

impl Arch {
    /// The architecture of ELF machine `e_machine`, if qld links it.
    #[must_use]
    pub fn from_machine(e_machine: u16) -> Option<Self> {
        match e_machine {
            EM_X86_64 => Some(Self::X86_64),
            EM_AARCH64 => Some(Self::AArch64),
            EM_RISCV => Some(Self::RiscV64),
            EM_LOONGARCH => Some(Self::LoongArch64),
            EM_PPC64 => Some(Self::Ppc64),
            crate::elf::read::consts::EM_386 => Some(Self::I386),
            crate::elf::read::consts::EM_S390 => Some(Self::S390x),
            crate::elf::read::consts::EM_ARM => Some(Self::Arm),
            _ => None,
        }
    }

    /// The architecture of `target`, if qld links it.
    #[must_use]
    pub fn from_target(target: Target) -> Option<Self> {
        match target.arch {
            Architecture::X86_64 => Some(Self::X86_64),
            Architecture::Aarch64 => Some(Self::AArch64),
            // Only little-endian RISC-V: `elf64briscv` needs big-endian ELF.
            Architecture::Riscv64 if target.endian == crate::target::Endianness::Little => {
                Some(Self::RiscV64)
            }
            Architecture::Riscv32 if target.endian == crate::target::Endianness::Little => {
                Some(Self::RiscV32)
            }
            Architecture::LoongArch64 => Some(Self::LoongArch64),
            Architecture::X86 => Some(Self::I386),
            Architecture::X86_64X32 => Some(Self::X32),
            // Only little-endian Arm: BE8 output is not implemented.
            Architecture::Arm if target.endian == crate::target::Endianness::Little => {
                Some(Self::Arm)
            }
            Architecture::PowerPc64 if target.endian == crate::target::Endianness::Little => {
                Some(Self::Ppc64)
            }
            Architecture::S390x => Some(Self::S390x),
            _ => None,
        }
    }

    /// The architecture of a link: the emulation (`-m`) when one was given,
    /// otherwise the first relocatable object's machine, otherwise the
    /// default target's ([`crate::elf::target::default_target`]).
    #[must_use]
    pub fn of<F: crate::elf::read::ElfFormat>(
        options: &LinkOptions,
        files: &[super::inputs::ElfInput<'_, F>],
    ) -> Self {
        options
            .target
            .and_then(Self::from_target)
            .or_else(|| Self::of_files(files))
            .or_else(|| Self::from_target(crate::elf::target::default_target()))
            .unwrap_or_default()
    }

    /// The architecture of the first relocatable object among `files`.
    #[must_use]
    pub fn of_files<F: crate::elf::read::ElfFormat>(
        files: &[super::inputs::ElfInput<'_, F>],
    ) -> Option<Self> {
        files.iter().find_map(|file| {
            let object = file.object.as_ref()?;
            Self::from_machine(object.elf.elf().header().e_machine)
                .map(|arch| arch.for_word_size(F::WORD_SIZE))
        })
    }

    /// The variant of `self` for an ELF class whose words are `word_size`
    /// bytes: RISC-V is one machine in both classes, and so are x86-64
    /// and x32.
    #[must_use]
    pub fn for_word_size(self, word_size: usize) -> Self {
        match self {
            Self::RiscV64 if word_size == 4 => Self::RiscV32,
            // An ELF32 x86-64 object is x32.
            Self::X86_64 if word_size == 4 => Self::X32,
            _ => self,
        }
    }

    /// Whether this is RISC-V, of either width: both share one backend
    /// ([`riscv`]), relaxation and `.riscv.attributes` included.
    #[must_use]
    #[inline]
    pub fn is_riscv(self) -> bool {
        matches!(self, Self::RiscV64 | Self::RiscV32)
    }

    /// Why object `file` cannot be linked with the others, if it cannot
    /// (RISC-V: a floating-point ABI other than the first object's).
    #[must_use]
    pub fn incompatible<F: crate::elf::read::ElfFormat>(
        self,
        files: &[super::inputs::ElfInput<'_, F>],
        file: usize,
    ) -> Option<String> {
        if !self.is_riscv() {
            return None;
        }
        // RISC-V objects only: not `-b binary` inputs, which are `EM_NONE`.
        let flags = |f: &super::inputs::ElfInput<'_, F>| {
            let header = f.object.as_ref()?.elf.elf().header();
            (header.e_machine == crate::elf::read::consts::EM_RISCV).then_some(header.e_flags)
        };
        let (first_index, first) = files
            .iter()
            .enumerate()
            .find_map(|(i, f)| Some((i, flags(f)?)))?;
        let this = files.get(file)?;
        let what = riscv::incompatible_flags(first, flags(this)?)?;
        let first_name = files
            .get(first_index)
            .map(|f| f.display())
            .unwrap_or_default();
        Some(format!(
            "{}: cannot link object files with different {what} from {first_name}",
            this.display()
        ))
    }

    /// The ELF class and byte order of the output.
    ///
    /// Every encoder and decoder in the ELF backend is generic over the
    /// matching [`ElfFormat`](crate::elf::read::ElfFormat), so the choice is
    /// made once per link and the loops that follow never branch on it.
    #[must_use]
    pub fn kind(self) -> crate::elf::read::ElfKind {
        match self {
            Self::I386 | Self::X32 | Self::RiscV32 | Self::Arm => {
                crate::elf::read::ElfKind::Elf32Le
            }
            Self::S390x => crate::elf::read::ElfKind::Elf64Be,
            Self::X86_64 | Self::AArch64 | Self::RiscV64 | Self::LoongArch64 | Self::Ppc64 => {
                crate::elf::read::ElfKind::Elf64Le
            }
        }
    }

    /// The addend of `SHT_REL` relocation `r_type` at `offset` in section
    /// `data`: the contents of the field it patches (i386). Architectures
    /// that use `SHT_RELA` never store one there.
    #[must_use]
    #[inline]
    pub fn implicit_addend(self, r_type: u32, data: &[u8], offset: u64) -> i64 {
        match self {
            Self::I386 => i386::implicit_addend(r_type, data, offset),
            Self::Arm => arm::implicit_addend(r_type, data, offset),
            _ => 0,
        }
    }

    /// Whether dynamic relocations are `SHT_REL`, their addends stored in
    /// the words they relocate (i386), rather than `SHT_RELA`.
    #[must_use]
    pub fn uses_rel(self) -> bool {
        matches!(self, Self::I386 | Self::Arm)
    }

    /// Whether a field of `width` holds a whole address, so a dynamic
    /// relocation can fill it: 64 bits in ELF64, 32 in ELF32.
    #[must_use]
    #[inline]
    pub fn is_word(self, width: Width) -> bool {
        match self {
            Self::I386 | Self::Arm => matches!(width, Width::Any32 | Width::U32 | Width::I32),
            // `R_X86_64_32`, GNU ld's pointer relocation for x32.
            Self::X32 => width == Width::U32,
            Self::RiscV32 => width == Width::RiscV(crate::arch::riscv::Field::Word32),
            _ => width == Width::W64,
        }
    }

    /// Size of one GOT or `.got.plt` entry: the class's word, except on
    /// x32, whose GOT entries are 8 bytes as on x86-64 (indirect calls and
    /// jumps read 64 bits, and TLS entries hold 64-bit offsets).
    #[must_use]
    #[inline]
    pub fn got_entry_size(self) -> u64 {
        if self == Self::X32 {
            8
        } else {
            self.kind().word_size()
        }
    }

    /// Size of one dynamic relocation entry.
    #[must_use]
    pub fn dyn_reloc_size(self) -> u64 {
        if self.uses_rel() {
            self.kind().rel_size()
        } else {
            self.kind().rela_size()
        }
    }

    /// The `e_machine` of the output.
    #[must_use]
    pub fn machine(self) -> u16 {
        match self {
            Self::I386 => crate::elf::read::consts::EM_386,
            Self::Arm => crate::elf::read::consts::EM_ARM,
            Self::X86_64 | Self::X32 => EM_X86_64,
            Self::AArch64 => EM_AARCH64,
            Self::RiscV64 | Self::RiscV32 => EM_RISCV,
            Self::LoongArch64 => EM_LOONGARCH,
            Self::Ppc64 => EM_PPC64,
            Self::S390x => crate::elf::read::consts::EM_S390,
        }
    }

    /// The GNU ld emulation name, for diagnostics.
    #[must_use]
    pub fn emulation(self) -> &'static str {
        match self {
            Self::I386 => "elf_i386",
            Self::Arm => "armelf_linux_eabi",
            Self::X86_64 => "elf_x86_64",
            Self::X32 => "elf32_x86_64",
            Self::AArch64 => "aarch64linux",
            Self::RiscV64 => "elf64lriscv",
            Self::RiscV32 => "elf32lriscv",
            Self::LoongArch64 => "elf64loongarch",
            Self::Ppc64 => "elf64lppc",
            Self::S390x => "elf64_s390",
        }
    }

    /// The name of relocation type `r_type`, as `readelf` prints it.
    #[must_use]
    pub fn reloc_name(self, r_type: u32) -> Option<&'static str> {
        match self {
            Self::LoongArch64 => loongarch::reloc_name(r_type),
            Self::S390x => s390x::reloc_name(r_type),
            Self::Arm => arm::reloc_name(r_type),
            _ => reloc_name(self.machine(), r_type),
        }
    }

    /// That name, or the number when the type is unknown.
    #[must_use]
    pub fn reloc_label(self, r_type: u32) -> String {
        let r_type = match self {
            Self::LoongArch64 => loongarch::base_type(r_type),
            Self::Ppc64 => ppc64::base_type(r_type),
            _ => r_type,
        };
        self.reloc_name(r_type)
            .map_or_else(|| r_type.to_string(), str::to_owned)
    }

    /// The default maximum page size: what segment alignment assumes when
    /// `-z max-page-size` is not given.
    #[must_use]
    pub fn default_max_page(self) -> u64 {
        match self {
            // Arm Linux has 4 KiB pages and GNU ld's Arm backend assumes
            // them; lld assumes 64 KiB there, which pads every segment.
            Self::I386
            | Self::S390x
            | Self::X86_64
            | Self::X32
            | Self::RiscV64
            | Self::RiscV32
            | Self::Arm => 0x1000,
            Self::AArch64 | Self::Ppc64 => 0x1_0000,
            // GNU ld's; lld assumes 64 KiB.
            Self::LoongArch64 => 0x4000,
        }
    }

    /// The address a non-PIE executable is linked at by default (GNU ld's
    /// text start, headers included).
    #[must_use]
    pub fn default_base(self) -> u64 {
        match self {
            Self::I386 => 0x0804_8000,
            Self::X86_64 | Self::X32 | Self::AArch64 => super::layout::DEFAULT_BASE,
            Self::RiscV64 | Self::RiscV32 | Self::Arm => 0x1_0000,
            Self::LoongArch64 => 0x1_2000_0000,
            // The first 256 MiB segment boundary.
            Self::Ppc64 => 0x1000_0000,
            Self::S390x => 0x100_0000,
        }
    }

    /// The number of words `.got.plt` reserves for the dynamic linker:
    /// `_DYNAMIC`, the link map and the resolver on x86-64 and AArch64; the
    /// resolver and the link map on RISC-V, LoongArch and PowerPC64.
    #[must_use]
    pub fn got_plt_reserved(self) -> u64 {
        match self {
            Self::I386 | Self::S390x | Self::Arm => 3,
            Self::X86_64 | Self::X32 | Self::AArch64 => 3,
            Self::RiscV64 | Self::RiscV32 | Self::LoongArch64 | Self::Ppc64 => 2,
        }
    }

    /// The `e_flags` of the output, from the input objects: the LoongArch
    /// ABI and object ABI version, or the PowerPC64 ABI version (2); zero
    /// elsewhere.
    #[must_use]
    pub fn output_flags<F: crate::elf::read::ElfFormat>(
        self,
        files: &[super::inputs::ElfInput<'_, F>],
    ) -> u32 {
        if self == Self::Ppc64 {
            return ppc64::ABI_VERSION;
        }
        if self == Self::Arm {
            return arm::output_flags(arm::attributes::hard_float(files));
        }
        if self.is_riscv() {
            return riscv::output_flags(
                files
                    .iter()
                    .filter_map(|f| f.object.as_ref())
                    .map(|o| o.elf.elf().header().e_flags),
            );
        }
        if self != Self::LoongArch64 {
            return 0;
        }
        loongarch::output_flags(files.iter().filter_map(|file| {
            let object = file.object.as_ref()?;
            let header = object.elf.elf().header();
            if header.e_machine != EM_LOONGARCH {
                return None;
            }
            let code = object
                .sections
                .iter()
                .any(|section| section.header.sh_flags & SHF_EXECINSTR != 0);
            Some((header.e_flags, code))
        }))
    }

    /// Whether [`Arch::annotate`] changes anything on this architecture, so
    /// relocation loops must look one relocation ahead
    /// ([`for_each_relocation!`]).
    #[must_use]
    pub fn annotates(self) -> bool {
        matches!(self, Self::LoongArch64 | Self::Ppc64)
    }

    /// `rel` with what the architecture needs to know about the relocation
    /// that follows it (`next`) folded into its type: on LoongArch, whether
    /// an `R_LARCH_RELAX` allows the instructions to be relaxed
    /// ([`loongarch::RELAX_HINT`]); on PowerPC64, whether a
    /// `__tls_get_addr` marker is on a PC-relative call
    /// ([`ppc64::PCREL_CALL_HINT`]). Other architectures get `rel` back.
    #[must_use]
    pub fn annotate(self, rel: Relocation, next: Option<&Relocation>) -> Relocation {
        if self == Self::Ppc64 {
            return ppc64::annotate(rel, next);
        }
        if self == Self::LoongArch64
            && let Some(next) = next
            && next.r_type == loongarch::R_LARCH_RELAX
            && next.offset == rel.offset
        {
            return Relocation {
                r_type: rel.r_type | loongarch::RELAX_HINT,
                ..rel
            };
        }
        rel
    }

    /// The page delta a page-relative relocation `r_type` at `place`
    /// computes to `target`: `Page(target) - Page(place)`, adjusted on
    /// LoongArch for the sign of the low part that completes it.
    #[must_use]
    pub fn page_delta(self, target: u64, place: u64, r_type: u32) -> u64 {
        match self {
            Self::I386 | Self::S390x | Self::Arm => {
                crate::arch::aarch64::page(target).wrapping_sub(crate::arch::aarch64::page(place))
            }
            Self::LoongArch64 => loongarch::page_delta(target, place, r_type),
            Self::X86_64
            | Self::X32
            | Self::AArch64
            | Self::RiscV64
            | Self::RiscV32
            | Self::Ppc64 => {
                let page = crate::arch::aarch64::page;
                page(target).wrapping_sub(page(place))
            }
        }
    }

    /// Rewrites an instruction pair classified [`Kind::Relax`], given the
    /// value `target` (`S + A`) and the `place` of the relocation.
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when the rewrite does not apply.
    pub fn relax(
        self,
        out: &mut [u8],
        offset: u64,
        r_type: u32,
        target: u64,
        place: u64,
    ) -> Result<(), ApplyError> {
        match self {
            Self::I386 | Self::S390x | Self::Arm => Err(ApplyError::BadInstruction),
            Self::LoongArch64 => loongarch::relax(out, offset, r_type, target, place),
            Self::X86_64
            | Self::X32
            | Self::AArch64
            | Self::RiscV64
            | Self::RiscV32
            | Self::Ppc64 => Err(ApplyError::BadInstruction),
        }
    }

    /// Whether layout shrinks code sections by linker relaxation, so it
    /// iterates through [`shrink::layout`].
    #[must_use]
    pub fn relaxes(self) -> bool {
        shrink::applies(self)
    }

    /// Whether the entries of `.hash` are eight bytes wide rather than
    /// four: the s390x ABI's odd choice, which GNU ld implements in
    /// `s390_elf64_size_info`.
    #[must_use]
    pub fn wide_sysv_hash(self) -> bool {
        self == Self::S390x
    }

    /// Whether `.got.plt[0]` holds the address of `_DYNAMIC`.
    #[must_use]
    pub fn got_plt_holds_dynamic(self) -> bool {
        self.got_plt_reserved() == 3
    }

    /// Rejects options whose effect is not implemented, rather than
    /// silently producing a binary that does not have it.
    ///
    /// # Errors
    ///
    /// [`crate::error::Error::Unimplemented`] for `--emit-relocs` on Arm,
    /// whose `SHT_REL` relocations the emitter does not write.
    pub fn check_options(self, options: &LinkOptions) -> crate::error::Result<()> {
        if self == Self::Arm && options.emit_relocs {
            return Err(crate::error::Error::Unimplemented(
                "--emit-relocs for 32-bit Arm (SHT_REL relocations)".into(),
            ));
        }
        Ok(())
    }

    /// Rejects options a linker script layout does not implement: it
    /// places no thunk pool, so it has nowhere to put Cortex-A53 erratum
    /// patches.
    ///
    /// # Errors
    ///
    /// [`crate::error::Error::Unimplemented`] for the Cortex-A53 erratum
    /// workarounds.
    pub fn check_script_options(self, options: &LinkOptions) -> crate::error::Result<()> {
        if self == Self::AArch64 && aarch64_errata::enabled(options) {
            return Err(crate::error::Error::Unimplemented(
                "--fix-cortex-a53-843419 and --fix-cortex-a53-835769 with a linker script".into(),
            ));
        }
        Ok(())
    }

    /// Whether calls can fall out of range, so layout has to insert
    /// range-extension thunks.
    #[must_use]
    pub fn needs_thunks(self) -> bool {
        matches!(self, Self::AArch64 | Self::Ppc64 | Self::Arm)
    }

    /// Number of bytes one range-extension thunk occupies.
    #[must_use]
    pub fn thunk_size(self) -> u64 {
        match self {
            Self::Ppc64 => crate::arch::ppc64::THUNK_SIZE,
            Self::Arm => crate::arch::arm::THUNK_SIZE,
            _ => crate::arch::aarch64::THUNK_SIZE,
        }
    }

    /// Writes the range-extension thunk at address `address` for thunk key
    /// `key` ([`Arch::branch_thunk`]) into `out` at `at`.
    ///
    /// # Errors
    ///
    /// [`ApplyError::Overflow`] when the target is out of the thunk's reach.
    pub fn write_thunk(
        self,
        out: &mut [u8],
        at: u64,
        address: u64,
        key: u64,
    ) -> Result<(), ApplyError> {
        match self {
            Self::Ppc64 => crate::arch::ppc64::write_thunk(out, at, address, key)
                .map_err(|_| ApplyError::Overflow),
            Self::Arm => arm::write_thunk(out, at, address, key),
            _ => crate::arch::aarch64::write_thunk(out, at, address, key)
                .map_err(|_| ApplyError::Overflow),
        }
    }

    /// Whether relocation `r_type` is a direct branch that range-extension
    /// thunks serve.
    #[must_use]
    pub fn is_thunk_branch(self, r_type: u32) -> bool {
        use crate::elf::read::consts::aarch64 as a64;
        match self {
            Self::I386 | Self::S390x => false,
            Self::Arm => arm::is_thunk_branch(r_type),
            Self::X86_64 | Self::X32 | Self::RiscV64 | Self::RiscV32 | Self::LoongArch64 => false,
            Self::AArch64 => matches!(r_type, a64::R_AARCH64_CALL26 | a64::R_AARCH64_JUMP26),
            Self::Ppc64 => ppc64::is_thunk_branch(r_type),
        }
    }

    /// The address a direct branch jumps to, before any thunk: PowerPC64
    /// enters a function of this output at its local entry point.
    #[must_use]
    pub fn branch_destination(self, branch: Branch) -> u64 {
        match self {
            Self::Ppc64 => ppc64::branch_destination(branch),
            _ => branch.target,
        }
    }

    /// The key of the range-extension thunk `branch` goes through, if it
    /// needs one: its destination (thunks are shared by key), on PowerPC64
    /// with the kind of thunk in the low bits.
    #[must_use]
    pub fn branch_thunk(self, branch: Branch) -> Option<u64> {
        match self {
            Self::I386 | Self::S390x | Self::Arm => None,
            // Arm branches are planned by `arm::thunks`, which knows the
            // instruction set of both ends.
            Self::X86_64 | Self::X32 | Self::RiscV64 | Self::RiscV32 | Self::LoongArch64 => None,
            Self::AArch64 => (self.is_thunk_branch(branch.r_type)
                && !crate::arch::aarch64::branch_in_range(branch.place, branch.target))
            .then_some(branch.target),
            Self::Ppc64 => ppc64::branch_thunk(branch),
        }
    }

    /// Rewrites what a direct call at `offset` needs besides its
    /// displacement: on PowerPC64, the `nop` after a call through a stub
    /// becomes the reload of the TOC pointer.
    ///
    /// # Errors
    ///
    /// [`ApplyError::BadInstruction`] for calls the architecture cannot
    /// link.
    pub fn finish_call(
        self,
        out: &mut [u8],
        offset: u64,
        branch: Branch,
    ) -> Result<(), ApplyError> {
        match self {
            Self::Ppc64 => ppc64::finish_call(out, offset, branch),
            _ => Ok(()),
        }
    }

    /// Whether `-z separate-code` is the default, as it is for GNU ld's
    /// x86 targets but not for AArch64.
    #[must_use]
    pub fn separate_code_by_default(self) -> bool {
        matches!(self, Self::X86_64 | Self::X32 | Self::I386)
    }

    /// The default program interpreter on Linux.
    #[must_use]
    pub fn default_interpreter(self) -> &'static str {
        match self {
            Self::I386 => "/lib/ld-linux.so.2",
            Self::Arm => arm::INTERPRETER,
            Self::X86_64 => "/lib64/ld-linux-x86-64.so.2",
            Self::X32 => "/libx32/ld-linux-x32.so.2",
            Self::AArch64 => "/lib/ld-linux-aarch64.so.1",
            Self::RiscV64 | Self::RiscV32 => {
                riscv::interpreter(riscv::EF_RISCV_FLOAT_ABI, self.kind().word_size())
            }
            Self::LoongArch64 => "/lib64/ld-linux-loongarch-lp64d.so.1",
            Self::Ppc64 => "/lib64/ld64.so.2",
            Self::S390x => "/lib/ld64.so.1",
        }
    }

    /// Whether TLS uses variant I (the thread pointer is below the block,
    /// after a two-word thread control block) rather than variant II.
    #[must_use]
    pub fn tls_variant1(self) -> bool {
        matches!(
            self,
            Self::AArch64
                | Self::RiscV64
                | Self::RiscV32
                | Self::LoongArch64
                | Self::Ppc64
                | Self::Arm
        )
    }

    /// The size of the thread control block variant I reserves below the
    /// TLS block.
    #[must_use]
    pub fn tcb_size(self) -> u64 {
        match self {
            Self::I386 | Self::S390x => 0,
            Self::X86_64
            | Self::X32
            | Self::RiscV64
            | Self::RiscV32
            | Self::LoongArch64
            | Self::Ppc64 => 0,
            Self::AArch64 => 16,
            Self::Arm => 8,
        }
    }

    /// Where the thread pointer is relative to the start of the TLS block,
    /// when the ABI fixes it there (PowerPC64: 0x7000 bytes past it)
    /// rather than past a thread control block.
    #[must_use]
    pub fn tp_past_tls_start(self) -> Option<u64> {
        match self {
            Self::Ppc64 => Some(crate::arch::ppc64::TP_OFFSET),
            _ => None,
        }
    }

    /// How far past the start of a module's TLS block the dynamic thread
    /// vector points (PowerPC64: 0x8000, RISC-V: 0x800), which biases
    /// `@dtprel` values.
    #[must_use]
    pub fn dtv_offset(self) -> u64 {
        match self {
            Self::Ppc64 => crate::arch::ppc64::DTV_OFFSET,
            Self::RiscV64 | Self::RiscV32 => crate::arch::riscv::DTP_OFFSET,
            _ => 0,
        }
    }

    /// Where the GOT base that GOT-relative relocations use is, from the
    /// start of `.got`, when it is not `.got.plt` (PowerPC64: the TOC
    /// pointer, `.got + 0x8000`).
    #[must_use]
    pub fn toc_bias(self) -> Option<u64> {
        match self {
            Self::Ppc64 => Some(crate::arch::ppc64::TOC_BIAS),
            _ => None,
        }
    }

    /// Words reserved at the start of `.got` (PowerPC64 keeps the TOC
    /// pointer's link-time value there).
    #[must_use]
    pub fn got_header_words(self) -> u64 {
        match self {
            Self::Ppc64 => 1,
            _ => 0,
        }
    }

    /// The `DT_PPC64_GLINK` value, as an offset from the start of `.plt`:
    /// 32 bytes before the first lazy entry, where glibc expects it.
    #[must_use]
    pub fn glink_offset(self) -> Option<u64> {
        match self {
            Self::Ppc64 => Some(crate::arch::ppc64::GLINK_HEADER_SIZE.wrapping_sub(32)),
            _ => None,
        }
    }

    /// Whether a dynamic output calls PLT entries through `.plt.sec`:
    /// x86-64 with IBT, and PowerPC64 always, its call stubs being there
    /// while `.plt` holds the lazy-binding entries.
    #[must_use]
    pub fn has_plt_sec(self, ibt: bool) -> bool {
        match self {
            Self::I386 | Self::X86_64 | Self::X32 => ibt,
            Self::AArch64
            | Self::RiscV64
            | Self::RiscV32
            | Self::LoongArch64
            | Self::S390x
            | Self::Arm => false,
            Self::Ppc64 => true,
        }
    }

    /// Size of one `.plt.sec` entry.
    #[must_use]
    pub fn plt_sec_entry_size(self, flags: PltFlags) -> u64 {
        match self {
            Self::Ppc64 => crate::arch::ppc64::PLT_CALL_STUB_SIZE,
            _ => self.plt_entry_size(flags),
        }
    }

    /// Whether a preemptible function that also has a GOT entry is called
    /// through `.plt.got` (jumping through that entry) rather than getting
    /// a PLT slot. PowerPC64 linkers give every called function a slot, and
    /// so do GNU ld's AArch64 and s390x backends, which have no `.plt.got`.
    #[must_use]
    pub fn uses_plt_got(self) -> bool {
        !matches!(self, Self::Ppc64 | Self::AArch64 | Self::S390x | Self::Arm)
    }

    /// Whether a dynamic output's `IRELATIVE` relocations go to
    /// `.rela.plt`, with the lazy PLT relocations. PowerPC64's dynamic
    /// linker sets the lazy slots up itself and never applies `.rela.plt`
    /// entries one by one, so GNU ld puts them in `.rela.dyn` there.
    #[must_use]
    pub fn irelative_in_rela_plt(self) -> bool {
        self != Self::Ppc64
    }

    /// The number written for dynamic relocation `kind`.
    #[must_use]
    pub fn dyn_reloc(self, kind: DynKind) -> u32 {
        use crate::elf::read::consts::{aarch64 as a64, ppc64 as p64, riscv as rv, x86_64 as x64};
        match self {
            Self::I386 => {
                use crate::elf::read::consts::i386 as x86;
                match kind {
                    DynKind::Relative => x86::R_386_RELATIVE,
                    DynKind::Irelative => x86::R_386_IRELATIVE,
                    DynKind::JumpSlot => x86::R_386_JUMP_SLOT,
                    DynKind::GlobDat => x86::R_386_GLOB_DAT,
                    DynKind::Copy => x86::R_386_COPY,
                    DynKind::Abs64 => x86::R_386_32,
                    DynKind::DtpMod => x86::R_386_TLS_DTPMOD32,
                    DynKind::DtpOff => x86::R_386_TLS_DTPOFF32,
                    DynKind::TpOff => x86::R_386_TLS_TPOFF,
                    DynKind::TlsDesc => x86::R_386_TLS_DESC,
                }
            }
            Self::Arm => match kind {
                DynKind::Relative => arm::R_ARM_RELATIVE,
                DynKind::Irelative => arm::R_ARM_IRELATIVE,
                DynKind::JumpSlot => arm::R_ARM_JUMP_SLOT,
                DynKind::GlobDat => arm::R_ARM_GLOB_DAT,
                DynKind::Copy => arm::R_ARM_COPY,
                DynKind::Abs64 => arm::R_ARM_ABS32,
                DynKind::DtpMod => arm::R_ARM_TLS_DTPMOD32,
                DynKind::DtpOff => arm::R_ARM_TLS_DTPOFF32,
                DynKind::TpOff => arm::R_ARM_TLS_TPOFF32,
                DynKind::TlsDesc => arm::R_ARM_TLS_DESC,
            },
            Self::X86_64 | Self::X32 => match kind {
                DynKind::Relative => x64::R_X86_64_RELATIVE,
                DynKind::Irelative => x64::R_X86_64_IRELATIVE,
                DynKind::JumpSlot => x64::R_X86_64_JUMP_SLOT,
                DynKind::GlobDat => x64::R_X86_64_GLOB_DAT,
                DynKind::Copy => x64::R_X86_64_COPY,
                // x32 pointers are 32 bits: `R_X86_64_32`, as GNU ld writes.
                DynKind::Abs64 if self == Self::X32 => x64::R_X86_64_32,
                DynKind::Abs64 => x64::R_X86_64_64,
                DynKind::DtpMod => x64::R_X86_64_DTPMOD64,
                DynKind::DtpOff => x64::R_X86_64_DTPOFF64,
                DynKind::TpOff => x64::R_X86_64_TPOFF64,
                DynKind::TlsDesc => x64::R_X86_64_TLSDESC,
            },
            Self::AArch64 => match kind {
                DynKind::Relative => a64::R_AARCH64_RELATIVE,
                DynKind::Irelative => a64::R_AARCH64_IRELATIVE,
                DynKind::JumpSlot => a64::R_AARCH64_JUMP_SLOT,
                DynKind::GlobDat => a64::R_AARCH64_GLOB_DAT,
                DynKind::Copy => a64::R_AARCH64_COPY,
                DynKind::Abs64 => a64::R_AARCH64_ABS64,
                DynKind::DtpMod => a64::R_AARCH64_TLS_DTPMOD64,
                DynKind::DtpOff => a64::R_AARCH64_TLS_DTPREL64,
                DynKind::TpOff => a64::R_AARCH64_TLS_TPREL64,
                DynKind::TlsDesc => a64::R_AARCH64_TLSDESC,
            },
            Self::RiscV64 => match kind {
                DynKind::Relative => rv::R_RISCV_RELATIVE,
                DynKind::Irelative => rv::R_RISCV_IRELATIVE,
                DynKind::JumpSlot => rv::R_RISCV_JUMP_SLOT,
                DynKind::GlobDat | DynKind::Abs64 => rv::R_RISCV_64,
                DynKind::Copy => rv::R_RISCV_COPY,
                DynKind::DtpMod => rv::R_RISCV_TLS_DTPMOD64,
                DynKind::DtpOff => rv::R_RISCV_TLS_DTPREL64,
                DynKind::TpOff => rv::R_RISCV_TLS_TPREL64,
                DynKind::TlsDesc => rv::R_RISCV_TLSDESC,
            },
            // RV32 has no 64-bit dynamic relocations: a word is 32 bits.
            Self::RiscV32 => match kind {
                DynKind::Relative => rv::R_RISCV_RELATIVE,
                DynKind::Irelative => rv::R_RISCV_IRELATIVE,
                DynKind::JumpSlot => rv::R_RISCV_JUMP_SLOT,
                DynKind::GlobDat | DynKind::Abs64 => rv::R_RISCV_32,
                DynKind::Copy => rv::R_RISCV_COPY,
                DynKind::DtpMod => rv::R_RISCV_TLS_DTPMOD32,
                DynKind::DtpOff => rv::R_RISCV_TLS_DTPREL32,
                DynKind::TpOff => rv::R_RISCV_TLS_TPREL32,
                DynKind::TlsDesc => rv::R_RISCV_TLSDESC,
            },
            // LoongArch has no GLOB_DAT: a GOT slot takes the symbolic
            // 64-bit relocation.
            Self::LoongArch64 => match kind {
                DynKind::Relative => loongarch::R_LARCH_RELATIVE,
                DynKind::Irelative => loongarch::R_LARCH_IRELATIVE,
                DynKind::JumpSlot => loongarch::R_LARCH_JUMP_SLOT,
                DynKind::GlobDat | DynKind::Abs64 => loongarch::R_LARCH_64,
                DynKind::Copy => loongarch::R_LARCH_COPY,
                DynKind::DtpMod => loongarch::R_LARCH_TLS_DTPMOD64,
                DynKind::DtpOff => loongarch::R_LARCH_TLS_DTPREL64,
                DynKind::TpOff => loongarch::R_LARCH_TLS_TPREL64,
                DynKind::TlsDesc => loongarch::R_LARCH_TLS_DESC64,
            },
            Self::Ppc64 => match kind {
                DynKind::Relative => p64::R_PPC64_RELATIVE,
                DynKind::Irelative => p64::R_PPC64_IRELATIVE,
                DynKind::JumpSlot => p64::R_PPC64_JMP_SLOT,
                DynKind::GlobDat => p64::R_PPC64_GLOB_DAT,
                DynKind::Copy => p64::R_PPC64_COPY,
                DynKind::Abs64 => p64::R_PPC64_ADDR64,
                DynKind::DtpMod => p64::R_PPC64_DTPMOD64,
                DynKind::DtpOff => p64::R_PPC64_DTPREL64,
                DynKind::TpOff => p64::R_PPC64_TPREL64,
                // PowerPC64 has no TLS descriptors.
                DynKind::TlsDesc => p64::R_PPC64_NONE,
            },
            Self::S390x => match kind {
                DynKind::Relative => s390x::R_390_RELATIVE,
                DynKind::Irelative => s390x::R_390_IRELATIVE,
                DynKind::JumpSlot => s390x::R_390_JMP_SLOT,
                DynKind::GlobDat => s390x::R_390_GLOB_DAT,
                DynKind::Copy => s390x::R_390_COPY,
                DynKind::Abs64 => s390x::R_390_64,
                DynKind::DtpMod => s390x::R_390_TLS_DTPMOD,
                DynKind::DtpOff => s390x::R_390_TLS_DTPOFF,
                DynKind::TpOff => s390x::R_390_TLS_TPOFF,
                // s390x has no TLS descriptors.
                DynKind::TlsDesc => s390x::R_390_NONE,
            },
        }
    }

    /// Whether relocation `r_type` is a call or jump that goes through the
    /// PLT when its symbol is preemptible, and does not take the symbol's
    /// address (so `--icf=safe` may fold its target).
    #[must_use]
    #[inline(always)]
    pub fn is_branch(self, r_type: u32) -> bool {
        use crate::elf::read::consts::{aarch64 as a64, ppc64 as p64, x86_64 as x64};
        // x86-64 first, so that it pays for no other architecture.
        if self == Self::X86_64 {
            return matches!(r_type, x64::R_X86_64_PLT32 | x64::R_X86_64_PLT32_BND);
        }
        match self {
            Self::I386 => r_type == crate::elf::read::consts::i386::R_386_PLT32,
            Self::Arm => arm::is_branch(r_type),
            Self::X86_64 => false, // answered above
            Self::X32 => matches!(r_type, x64::R_X86_64_PLT32 | x64::R_X86_64_PLT32_BND),
            Self::Ppc64 => matches!(r_type, p64::R_PPC64_REL24 | p64::R_PPC64_REL24_NOTOC),
            Self::AArch64 => matches!(
                r_type,
                a64::R_AARCH64_CALL26 | a64::R_AARCH64_JUMP26 | a64::R_AARCH64_PLT32
            ),
            Self::RiscV64 | Self::RiscV32 => riscv::is_branch(r_type),
            Self::LoongArch64 => loongarch::is_branch(r_type),
            Self::S390x => s390x::is_branch(r_type),
        }
    }

    /// Classifies relocation `r_type` at `offset` in section `data`.
    ///
    /// # Errors
    ///
    /// [`ClassifyError`] for unsupported types and unrecognized TLS code.
    // Only a dispatch: each architecture's classifier stays out of line.
    #[inline(always)]
    pub fn classify(
        self,
        r_type: u32,
        addend: i64,
        data: &[u8],
        offset: u64,
        context: ClassifyContext,
    ) -> Result<Class, ClassifyError> {
        match self {
            Self::I386 => i386::classify(r_type, addend, data, offset, context),
            Self::Arm => arm::classify(r_type, context),
            Self::X86_64 => x86_64::classify(r_type, addend, data, offset, context),
            Self::X32 => x86_64::classify_x32(r_type, addend, data, offset, context),
            Self::AArch64 => aarch64::classify(r_type, context),
            Self::RiscV64 | Self::RiscV32 => riscv::classify(r_type, context),
            Self::LoongArch64 => loongarch::classify(r_type, addend, data, offset, context),
            Self::Ppc64 => ppc64::classify(r_type, data, offset, context),
            Self::S390x => s390x::classify(r_type, data, offset, context),
        }
    }

    /// Rewrites a relaxed GOT-indirect instruction (x86-64 only).
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when the instruction is not one that was classified as
    /// relaxable.
    pub fn relax_got(
        self,
        out: &mut [u8],
        offset: u64,
        kind: Kind,
        value: i64,
    ) -> Result<(), ApplyError> {
        match self {
            Self::I386 => i386::relax_got(out, offset, kind, value),
            Self::X86_64 => x86_64::relax_got(out, offset, kind, value),
            Self::X32 => x86_64::relax_got_x32(out, offset, kind, value),
            Self::AArch64
            | Self::RiscV64
            | Self::RiscV32
            | Self::LoongArch64
            | Self::Ppc64
            | Self::S390x
            | Self::Arm => Err(ApplyError::BadInstruction),
        }
    }

    /// Writes a GOT load classified [`Kind::GotRelax`], given the symbol's
    /// address and, in `values`, the GOT entry's address plus the addend
    /// ([`RelaxValues::got`]), the place and the GOT base.
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when a field does not fit.
    #[inline(never)]
    pub fn relax_got_load(
        self,
        out: &mut [u8],
        offset: u64,
        r_type: u32,
        symbol: u64,
        values: RelaxValues,
    ) -> Result<(), ApplyError> {
        match self {
            Self::S390x => s390x::relax_got(out, offset, r_type, symbol, values),
            _ => Err(ApplyError::BadInstruction),
        }
    }

    /// Rewrites a relaxed TLS access.
    ///
    /// # Errors
    ///
    /// [`ApplyError`] for unrecognized instruction sequences.
    pub fn relax_tls(
        self,
        out: &mut [u8],
        offset: u64,
        kind: Kind,
        r_type: u32,
        values: RelaxValues,
    ) -> Result<(), ApplyError> {
        match self {
            Self::I386 => i386::relax_tls(out, offset, kind, r_type, values),
            Self::X86_64 => x86_64::relax_tls(out, offset, kind, values),
            Self::X32 => x86_64::relax_tls_x32(out, offset, kind, values),
            Self::AArch64 => aarch64::relax_tls(out, offset, kind, r_type, values),
            // RISC-V and Arm sections are written by their own writers.
            Self::RiscV64 | Self::RiscV32 | Self::Arm => Err(ApplyError::BadInstruction),
            Self::LoongArch64 => loongarch::relax_tls(out, offset, kind, r_type, values),
            Self::Ppc64 => ppc64::relax_tls(out, offset, kind, r_type, values),
            Self::S390x => s390x::relax_tls(out, offset, kind, r_type, values),
        }
    }

    /// Size of the PLT header (`.plt` starts with it in a dynamic output).
    #[must_use]
    pub fn plt_header_size(self, flags: PltFlags) -> u64 {
        match self {
            Self::I386 => 16,
            Self::Arm => arm::PLT_HEADER_SIZE,
            Self::X86_64 | Self::X32 => 16,
            Self::AArch64 => {
                let _ = flags;
                32
            }
            Self::RiscV64 | Self::RiscV32 => riscv::PLT_HEADER_SIZE,
            Self::LoongArch64 => loongarch::PLT_HEADER_SIZE,
            Self::Ppc64 => crate::arch::ppc64::GLINK_HEADER_SIZE,
            Self::S390x => s390x::PLT_HEADER_SIZE,
        }
    }

    /// Size of one `.plt` entry.
    #[must_use]
    pub fn plt_entry_size(self, flags: PltFlags) -> u64 {
        match self {
            Self::I386 => i386::PLT_ENTRY_SIZE,
            Self::Arm => arm::PLT_ENTRY_SIZE,
            Self::X86_64 | Self::X32 => 16,
            Self::AArch64 => aarch64::plt_entry_size(flags),
            Self::RiscV64 | Self::RiscV32 => riscv::PLT_ENTRY_SIZE,
            Self::LoongArch64 => loongarch::PLT_ENTRY_SIZE,
            Self::Ppc64 => 4,
            Self::S390x => s390x::PLT_ENTRY_SIZE,
        }
    }

    /// Size of one `.plt.got` entry.
    #[must_use]
    pub fn plt_got_entry_size(self, flags: PltFlags) -> u64 {
        match self {
            Self::I386 => {
                if flags.landing_pad {
                    i386::PLT_ENTRY_SIZE
                } else {
                    i386::PLT_GOT_ENTRY_SIZE
                }
            }
            Self::Arm => arm::PLT_ENTRY_SIZE,
            Self::X86_64 | Self::X32 if flags.landing_pad => 16,
            Self::X86_64 | Self::X32 => 8,
            Self::AArch64 => aarch64::plt_entry_size(aarch64::plt_got_flags(flags)),
            Self::RiscV64 | Self::RiscV32 => riscv::PLT_ENTRY_SIZE,
            Self::LoongArch64 => loongarch::PLT_ENTRY_SIZE,
            Self::Ppc64 => crate::arch::ppc64::PLT_CALL_STUB_SIZE,
            // No `.plt.got` (see `uses_plt_got`).
            Self::S390x => s390x::PLT_ENTRY_SIZE,
        }
    }

    /// Alignment of `.plt`, `.plt.sec` and `.plt.got`: GNU ld aligns the
    /// s390x and Arm `.plt` to 4.
    #[must_use]
    pub fn plt_align(self) -> u64 {
        if matches!(self, Self::S390x | Self::Arm) {
            4
        } else {
            16
        }
    }

    /// Alignment of a static executable's `.plt`, which holds only IFUNC
    /// stubs: GNU ld's i386 stubs are 8 bytes and aligned to 8.
    #[must_use]
    pub fn iplt_align(self) -> u64 {
        match self {
            Self::I386 => 8,
            Self::S390x | Self::Arm => 4,
            _ => 16,
        }
    }

    /// Size of an IFUNC stub in a static executable.
    #[must_use]
    pub fn iplt_entry_size(self, flags: PltFlags) -> u64 {
        match self {
            Self::I386 => i386::IPLT_ENTRY_SIZE,
            Self::Arm => arm::PLT_ENTRY_SIZE,
            Self::X86_64 | Self::X32 => 16,
            Self::AArch64 => aarch64::plt_entry_size(flags),
            Self::RiscV64 | Self::RiscV32 => riscv::PLT_ENTRY_SIZE,
            Self::LoongArch64 => loongarch::PLT_ENTRY_SIZE,
            Self::Ppc64 => crate::arch::ppc64::PLT_CALL_STUB_SIZE,
            Self::S390x => s390x::PLT_ENTRY_SIZE,
        }
    }

    /// The value a lazy `.got.plt` slot holds before the dynamic linker
    /// binds it: the code that pushes the relocation index and jumps to the
    /// resolver.
    #[must_use]
    pub fn lazy_slot_value(self, plt: u64, entry: u64, flags: PltFlags) -> u64 {
        match self {
            Self::I386 => {
                // The `push` after the jump, or the whole entry with IBT.
                if flags.landing_pad {
                    entry
                } else {
                    entry.wrapping_add(6)
                }
            }
            // The `push` after the jump, or the whole entry with IBT.
            Self::X86_64 | Self::X32 if flags.landing_pad => entry,
            Self::X86_64 | Self::X32 => entry.wrapping_add(6),
            // The header pushes and jumps; entries do not. On LoongArch the
            // header finds the index from the entry's return address.
            Self::AArch64 | Self::RiscV64 | Self::RiscV32 | Self::LoongArch64 | Self::Arm => plt,
            // The dynamic linker points every slot at its lazy entry.
            Self::Ppc64 => 0,
            // The second half of the entry.
            Self::S390x => entry.wrapping_add(crate::arch::s390x::PLT_LAZY_OFFSET),
        }
    }

    /// Writes the PLT header at address `plt`, which jumps to the resolver
    /// through `.got.plt` (at `got_plt`).
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when out of range.
    pub fn write_plt_header(
        self,
        out: &mut [u8],
        plt: u64,
        got_plt: u64,
        flags: PltFlags,
    ) -> Result<(), ApplyError> {
        match self {
            Self::I386 => i386::write_plt_header(out, got_plt, flags.pic),
            Self::Arm => arm::write_plt_header(out, plt, got_plt),
            Self::X86_64 | Self::X32 => x86_64::write_plt_header(out, plt, got_plt),
            Self::AArch64 => aarch64::write_plt_header(out, plt, got_plt, flags),
            Self::RiscV64 | Self::RiscV32 => {
                riscv::write_plt_header(out, plt, got_plt, self.kind().word_size())
            }
            Self::LoongArch64 => loongarch::write_plt_header(out, plt, got_plt),
            Self::Ppc64 => ppc64::write_plt_header(out, plt, got_plt),
            // `got_plt` is the GOT pointer on s390x (see `write_plt`).
            Self::S390x => s390x::write_plt_header(out, plt, got_plt),
        }
    }

    /// Writes `.plt` entry `index` at `entry`, which jumps through its
    /// `.got.plt` slot at `slot`.
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when out of range.
    pub fn write_plt_entry(
        self,
        out: &mut [u8],
        entry: u64,
        slot: u64,
        index: u32,
        plt: u64,
        flags: PltFlags,
    ) -> Result<(), ApplyError> {
        match self {
            Self::I386 => {
                // `.got.plt` slot `index` follows the three reserved words,
                // which start at the GOT base.
                let got = slot.wrapping_sub(u64::from(index).wrapping_add(3).wrapping_mul(4));
                i386::write_plt_entry(
                    out,
                    entry,
                    slot,
                    index,
                    plt,
                    got,
                    flags.pic,
                    flags.landing_pad,
                )
            }
            Self::Arm => arm::write_plt_entry(out, entry, slot),
            Self::X86_64 | Self::X32 => {
                x86_64::write_plt_entry(out, entry, slot, index, plt, flags.landing_pad)
            }
            Self::AArch64 => aarch64::write_plt_entry(out, entry, slot, flags),
            Self::RiscV64 | Self::RiscV32 => {
                riscv::write_plt_entry(out, entry, slot, self.kind().word_size())
            }
            Self::LoongArch64 => loongarch::write_plt_entry(out, entry, slot),
            Self::Ppc64 => ppc64::write_plt_entry(out, entry, plt),
            Self::S390x => s390x::write_plt_entry(out, entry, slot, index, plt),
        }
    }

    /// Writes a `.plt.sec` or `.plt.got` entry at `entry` that jumps through
    /// the GOT word at `slot`. `got_base` is the GOT base
    /// ([`crate::elf::values::Addresses::got_base`]), from which PowerPC64
    /// stubs address the slot.
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when out of range.
    pub fn write_plt_jump(
        self,
        out: &mut [u8],
        entry: u64,
        slot: u64,
        flags: PltFlags,
        got_base: u64,
    ) -> Result<(), ApplyError> {
        match self {
            Self::I386 => i386::write_plt_jump(out, slot, got_base, flags.pic, flags.landing_pad),
            Self::Arm => arm::write_plt_entry(out, entry, slot),
            Self::X86_64 | Self::X32 => x86_64::write_plt_jump(out, entry, slot, flags.landing_pad),
            Self::AArch64 => {
                aarch64::write_plt_entry(out, entry, slot, aarch64::plt_got_flags(flags))
            }
            Self::RiscV64 | Self::RiscV32 => {
                riscv::write_plt_entry(out, entry, slot, self.kind().word_size())
            }
            Self::LoongArch64 => loongarch::write_plt_entry(out, entry, slot),
            Self::Ppc64 => ppc64::write_call_stub(out, slot, got_base),
            // No `.plt.sec` or `.plt.got`.
            Self::S390x => Err(ApplyError::BadInstruction),
        }
    }

    /// Writes an IFUNC stub at `stub` that jumps through the GOT slot at
    /// `slot_address`; `got_base` as for [`Arch::write_plt_jump`].
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when out of range.
    pub fn write_iplt(
        self,
        out: &mut [u8],
        stub: u64,
        slot_address: u64,
        flags: PltFlags,
        got_base: u64,
    ) -> Result<(), ApplyError> {
        match self {
            Self::I386 => i386::write_iplt(out, slot_address, got_base, flags.pic),
            Self::Arm => arm::write_plt_entry(out, stub, slot_address),
            Self::X86_64 | Self::X32 => x86_64::write_iplt(out, stub, slot_address),
            // GNU ld writes IFUNC stubs as ordinary PLT entries, landing
            // pad and authentication included.
            Self::AArch64 => aarch64::write_plt_entry(out, stub, slot_address, flags),
            Self::RiscV64 | Self::RiscV32 => {
                riscv::write_plt_entry(out, stub, slot_address, self.kind().word_size())
            }
            Self::LoongArch64 => loongarch::write_plt_entry(out, stub, slot_address),
            Self::Ppc64 => ppc64::write_call_stub(out, slot_address, got_base),
            Self::S390x => s390x::write_iplt(out, stub, slot_address),
        }
    }

    /// Replaces a branch to an undefined weak symbol, which has no address
    /// to branch to, with the instruction GNU ld writes there (AArch64: a
    /// `nop`; LoongArch: a branch to itself, since address 0 is out of
    /// reach). Returns `false` when the architecture keeps the branch.
    ///
    /// # Errors
    ///
    /// [`ApplyError`] when the instruction is outside the section.
    pub fn nop_undefined_branch(
        self,
        out: &mut [u8],
        offset: u64,
        r_type: u32,
    ) -> Result<bool, ApplyError> {
        match self {
            Self::I386 | Self::S390x | Self::Arm => Ok(false),
            // Arm undefined weak branches are written by `arm::apply`.
            Self::X86_64 | Self::X32 | Self::RiscV64 | Self::RiscV32 => Ok(false),
            Self::LoongArch64 => loongarch::undefined_weak_branch(out, offset, r_type),
            Self::AArch64 => aarch64::nop_undefined_branch(out, offset, r_type),
            Self::Ppc64 => ppc64::nop_undefined_branch(out, offset, r_type),
        }
    }

    /// Fills `out` with no-op instructions, as the architecture's default
    /// fill does for gaps in executable sections.
    pub fn write_nops(self, out: &mut [u8]) {
        match self {
            Self::I386 => x86_64::write_nops(out),
            // GNU ld fills gaps in Arm code with zeros: no one instruction
            // is a `nop` in both A32 and Thumb.
            Self::Arm => out.fill(0),
            Self::X86_64 | Self::X32 => x86_64::write_nops(out),
            Self::AArch64 => aarch64::write_nops(out),
            Self::RiscV64 | Self::RiscV32 => riscv::write_nops(out),
            Self::LoongArch64 => loongarch::write_nops(out),
            Self::Ppc64 => ppc64::write_nops(out),
            Self::S390x => s390x::write_nops(out),
        }
    }
}

fn slot<const N: usize>(out: &mut [u8], at: u64) -> Result<&mut [u8; N], ApplyError> {
    let start = usize::try_from(at).map_err(|_| ApplyError::OutOfBounds)?;
    out.get_mut(start..)
        .and_then(|rest| rest.first_chunk_mut::<N>())
        .ok_or(ApplyError::OutOfBounds)
}

/// Writes `value` into the field of width `width` at `offset`, checking that
/// it fits, in little-endian byte order ([`write_value_as`]).
///
/// # Errors
///
/// [`ApplyError::Overflow`] or [`ApplyError::OutOfBounds`].
pub fn write_value(
    out: &mut [u8],
    offset: u64,
    width: Width,
    value: u64,
) -> Result<(), ApplyError> {
    write_value_as::<crate::elf::read::Little>(out, offset, width, value)
}

/// Writes `value` into the field of width `width` at `offset`, checking that
/// it fits. Data fields are stored in byte order `E`; instruction fields
/// in their architecture's.
///
/// # Errors
///
/// [`ApplyError::Overflow`] or [`ApplyError::OutOfBounds`].
pub fn write_value_as<E: crate::elf::read::Endian>(
    out: &mut [u8],
    offset: u64,
    width: Width,
    value: u64,
) -> Result<(), ApplyError> {
    let signed = value as i64;
    match width {
        Width::None => {}
        Width::W64 => *slot::<8>(out, offset)? = E::put_u64(value),
        Width::U32 => {
            let v = u32::try_from(value).map_err(|_| ApplyError::Overflow)?;
            *slot::<4>(out, offset)? = E::put_u32(v);
        }
        Width::I32 => {
            let v = i32::try_from(signed).map_err(|_| ApplyError::Overflow)?;
            *slot::<4>(out, offset)? = E::put_u32(v as u32);
        }
        Width::Any32 => {
            if i32::try_from(signed).is_err() && u32::try_from(value).is_err() {
                return Err(ApplyError::Overflow);
            }
            *slot::<4>(out, offset)? = E::put_u32(value as u32);
        }
        Width::Any16 => {
            if i16::try_from(signed).is_err() && u16::try_from(value).is_err() {
                return Err(ApplyError::Overflow);
            }
            *slot::<2>(out, offset)? = E::put_u16(value as u16);
        }
        Width::I16 => {
            let v = i16::try_from(signed).map_err(|_| ApplyError::Overflow)?;
            *slot::<2>(out, offset)? = E::put_u16(v as u16);
        }
        Width::Any8 => {
            if i8::try_from(signed).is_err() && u8::try_from(value).is_err() {
                return Err(ApplyError::Overflow);
            }
            *slot::<1>(out, offset)? = [value as u8];
        }
        Width::I8 => {
            let v = i8::try_from(signed).map_err(|_| ApplyError::Overflow)?;
            *slot::<1>(out, offset)? = [v as u8];
        }
        Width::RiscV(field) => riscv::write_field(out, offset, field, value)?,
        Width::Field(field) => {
            if field.bytes() == 2 {
                let word = slot::<2>(out, offset)?;
                let encoded = field
                    .encode(u32::from(u16::from_le_bytes(*word)), signed)
                    .map_err(|_| ApplyError::Overflow)?;
                *word = (encoded as u16).to_le_bytes();
            } else {
                let word = slot::<4>(out, offset)?;
                let encoded = field
                    .encode(u32::from_le_bytes(*word), signed)
                    .map_err(|_| ApplyError::Overflow)?;
                *word = encoded.to_le_bytes();
            }
        }
        Width::LoongArch(field) => loongarch::write_field(out, offset, field, value)?,
        Width::Ppc(field) => write_ppc64(out, offset, field, signed)?,
        Width::S390(field) => s390x::write_field(out, offset, field, value)?,
        Width::Arm(field) => write_arm(out, offset, field, signed)?,
    }
    Ok(())
}

/// Writes Arm field `field` at `offset`. Out of line, so that
/// [`write_value`] stays small for the other architectures.
#[inline(never)]
fn write_arm(
    out: &mut [u8],
    offset: u64,
    field: crate::arch::arm::Field,
    value: i64,
) -> Result<(), ApplyError> {
    let at = usize::try_from(offset).map_err(|_| ApplyError::OutOfBounds)?;
    let insn = field.read(out, at).ok_or(ApplyError::OutOfBounds)?;
    let encoded = field
        .encode(insn, value)
        .map_err(|_| ApplyError::Overflow)?;
    field.write(out, at, encoded).ok_or(ApplyError::OutOfBounds)
}

/// Writes PowerPC64 field `field` at `offset`. Out of line, so that
/// [`write_value`] stays small for the other architectures.
#[inline(never)]
fn write_ppc64(
    out: &mut [u8],
    offset: u64,
    field: crate::arch::ppc64::Field,
    value: i64,
) -> Result<(), ApplyError> {
    use crate::arch::ppc64::EncodeError;
    let error = |e: EncodeError| match e {
        EncodeError::Overflow => ApplyError::Overflow,
        EncodeError::BadInstruction => ApplyError::BadInstruction,
    };
    if field == crate::arch::ppc64::Field::PcrelOpt {
        // Rewrites two instructions, `value` bytes apart.
        return ppc64::relax_pcrel_opt(out, offset, value);
    }
    match field.bytes() {
        2 => {
            let half = slot::<2>(out, offset)?;
            *half = field
                .encode16(u16::from_le_bytes(*half), value)
                .map_err(error)?
                .to_le_bytes();
        }
        8 => {
            let words = slot::<8>(out, offset)?;
            let (prefix, suffix) = words.split_at_mut(4);
            let old = (u64::from(u32::from_le_bytes([
                prefix[0], prefix[1], prefix[2], prefix[3],
            ])) << 32)
                | u64::from(u32::from_le_bytes([
                    suffix[0], suffix[1], suffix[2], suffix[3],
                ]));
            let encoded = field.encode64(old, value).map_err(error)?;
            prefix.copy_from_slice(&((encoded >> 32) as u32).to_le_bytes());
            suffix.copy_from_slice(&(encoded as u32).to_le_bytes());
        }
        _ => {
            let word = slot::<4>(out, offset)?;
            *word = field
                .encode32(u32::from_le_bytes(*word), value)
                .map_err(error)?
                .to_le_bytes();
        }
    }
    Ok(())
}

/// Adds `delta` to the field of width `width` at `offset`, wrapping as the
/// label-difference relocations do ([`Kind::Add`]; [`Kind::Sub`] passes
/// the negated value), in little-endian byte order ([`add_value_as`]).
///
/// # Errors
///
/// [`ApplyError::OutOfBounds`], or [`ApplyError::BadInstruction`] for a
/// width that is not data.
pub fn add_value(out: &mut [u8], offset: u64, width: Width, delta: u64) -> Result<(), ApplyError> {
    add_value_as::<crate::elf::read::Little>(out, offset, width, delta)
}

/// [`add_value`] for data fields in byte order `E`.
///
/// # Errors
///
/// [`ApplyError::OutOfBounds`], or [`ApplyError::BadInstruction`] for a
/// width that is not data.
pub fn add_value_as<E: crate::elf::read::Endian>(
    out: &mut [u8],
    offset: u64,
    width: Width,
    delta: u64,
) -> Result<(), ApplyError> {
    match width {
        Width::W64 => {
            let word = slot::<8>(out, offset)?;
            *word = E::put_u64(E::u64(*word).wrapping_add(delta));
        }
        Width::U32 | Width::I32 | Width::Any32 => {
            let word = slot::<4>(out, offset)?;
            *word = E::put_u32(E::u32(*word).wrapping_add(delta as u32));
        }
        Width::Any16 | Width::I16 => {
            let word = slot::<2>(out, offset)?;
            *word = E::put_u16(E::u16(*word).wrapping_add(delta as u16));
        }
        Width::Any8 | Width::I8 => {
            let [byte] = slot::<1>(out, offset)?;
            *byte = byte.wrapping_add(delta as u8);
        }
        Width::LoongArch(field) => loongarch::add_field(out, offset, field, delta)?,
        Width::None
        | Width::Field(_)
        | Width::RiscV(_)
        | Width::Ppc(_)
        | Width::S390(_)
        | Width::Arm(_) => {
            return Err(ApplyError::BadInstruction);
        }
    }
    Ok(())
}

/// Runs `$body` for every relocation of `$relocations` (the
/// [`Relocations`](crate::elf::read::Relocations) of one section, whose
/// contents are `$data`), with `$rel` bound to it, as a `for` loop does
/// (`continue` and `break` work).
///
/// `SHT_REL` relocations get the addend stored in the field they patch
/// ([`Arch::implicit_addend`]). On architectures that [`Arch::annotates`],
/// `$rel` is [`Arch::annotate`]d with the relocation that follows it. Each
/// choice is made once, and the body is expanded into one loop per case,
/// so an architecture pays per relocation only for what it uses.
macro_rules! for_each_relocation {
    ($arch:expr, $relocations:expr, $data:expr, |$rel:ident| $body:block) => {{
        let arch: $crate::elf::arch::Arch = $arch;
        match $relocations {
            $crate::elf::read::Relocations::Rela(relas) => {
                if arch.annotates() {
                    let mut relocations = relas.iter().peekable();
                    while let Some(current) = relocations.next() {
                        let $rel = arch.annotate(current, relocations.peek());
                        $body
                    }
                } else {
                    for $rel in relas.iter() $body
                }
            }
            $crate::elf::read::Relocations::Rel(rels) => {
                let data: &[u8] = $data;
                for current in rels.iter() {
                    let $rel = $crate::elf::read::Relocation {
                        addend: arch.implicit_addend(current.r_type, data, current.offset),
                        ..current
                    };
                    $body
                }
            }
        }
    }};
}
pub(crate) use for_each_relocation;

/// The byte width of a relocation field.
#[must_use]
pub fn width_bytes(width: Width) -> usize {
    match width {
        Width::None => 0,
        Width::W64 => 8,
        Width::U32 | Width::I32 | Width::Any32 => 4,
        Width::Any16 | Width::I16 => 2,
        Width::Any8 | Width::I8 => 1,
        Width::Field(field) => field.bytes(),
        Width::RiscV(field) => field.bytes(),
        Width::LoongArch(field) => field.bytes(),
        Width::Ppc(field) => field.bytes(),
        Width::S390(field) => field.bytes(),
        Width::Arm(field) => field.bytes(),
    }
}