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
//! The ELF link driver: runs the pipeline in `docs/architecture.md` for an ELF
//! target, from resolved options to a written output file.
//!
//! Each stage lives in its own module; this file only sequences them and
//! turns problems into diagnostics:
//!
//! 1. [`inputs`]: search paths, archives, input scripts; then the thread
//!    pool is sized from the input size unless `--threads` was given (in a
//!    pool of more than 16 threads, every stage but the relocation scan and
//!    section merging runs in a pool of 16: see `Narrow`);
//! 2. [`resolve_symbols_with`] with [`ElfRules`], claiming COMDAT groups as
//!    rounds load files ([`resolve::ComdatHook`]), then dropping the
//!    discarded copies' sections;
//! 3. [`place`]: output section assignment;
//! 4. linker-defined symbols ([`defined`]);
//! 5. `.eh_frame` splitting, `--gc-sections` and `--why-live` ([`gc`]);
//! 6. the relocation scan ([`scan`]) and undefined symbols;
//! 7. common symbols, merged sections, `--icf` ([`icf`]), live `.eh_frame`
//!    records;
//! 8. synthetic sections and the symbol table plan;
//! 9. [`layout`], symbol addresses, [`write`](mod@write), and the link map
//!    ([`map`]).
//!
//! Relocatable output (`-r`) leaves after step 2: optional `--gc-sections`
//! (which then needs `-e` or `-u` roots), then [`relocatable`].

use std::time::Instant;

use rayon::prelude::*;

use crate::args::{LinkOptions, OutputKind, StripMode};
use crate::debug::tombstone::{Style as TombstoneStyle, Tombstones};
use crate::diag::{Diagnostic, DiagnosticSink};
use crate::elf::read::{Elf32Le, Elf64Be, Elf64Le, ElfKind};
use crate::error::{Error, Result};
use crate::input::FileTable;
use crate::passes::IcfMode;
#[cfg(doc)]
use crate::symbols::resolve_symbols_with;
use crate::symbols::{SymbolName, SymbolTable};

use super::common;
use super::defined;
use super::dso;
use super::dynsym;
use super::ehframe;
use super::export::{self, Mode};
use super::gc;
use super::icf;
use super::inputs::{self, InternalNames, parse_number};
use super::layout::{self, LayoutInput, TrailerSizes};
use super::map;
use super::merge;
use super::object::{ParseConfig, SectionKind, WrapTable};
use super::place;
use super::refs::{Def, Refs};
use super::reloc;
use super::relocatable;
use super::resolve::{self, ElfRules};
use super::rules::RuleSet;
use super::scan::{self, UndefinedRef};
use super::sections::Sections;
use super::symtab;
use super::synth::{self, Synth};
use super::values::Addresses;
use super::write::{self, WriteInput};
use super::xref;

/// At most this many references are listed per undefined symbol.
const MAX_REFERENCES: usize = 3;

/// Links an ELF output described by `options`.
///
/// Called by [`crate::link`] inside a rayon pool sized by `--threads`.
///
/// # Errors
///
/// Returns [`Error::Unimplemented`] for output kinds of later milestones,
/// [`Error::Reported`] when errors were reported to `diagnostics`, and any
/// I/O or parse error.
pub fn link(options: &LinkOptions, diagnostics: &dyn DiagnosticSink) -> Result<()> {
    // `-plugin` needs no check here: compiler drivers always pass it, and
    // an IR input is reported as Unimplemented (M6) when it is loaded.
    let prepared = super::script_layout::prepare(options)?;
    check_supported(&prepared.options)?;
    // The class and byte order are chosen once, here: everything below is
    // generic over them, so the pipeline is monomorphized and never checks
    // either at run time. Only the combinations some architecture uses are
    // instantiated.
    match input_kind(&prepared.options) {
        ElfKind::Elf64Le => link_as::<Elf64Le>(&prepared, diagnostics),
        ElfKind::Elf32Le => link_as::<Elf32Le>(&prepared, diagnostics),
        ElfKind::Elf64Be => link_as::<Elf64Be>(&prepared, diagnostics),
        kind @ ElfKind::Elf32Be => Err(Error::Unimplemented(format!(
            "big-endian ELF output ({kind:?}) needs a big-endian architecture (M4)"
        ))),
    }
}

/// The ELF class and byte order of the link: the emulation's (`-m`) when one
/// was given, else the first input's named on the command line that names
/// one (an object, a GCC LTO object, LLVM bitcode, or the first such member
/// of an archive), else the default target's ([`super::target`]).
pub(crate) fn input_kind(options: &LinkOptions) -> ElfKind {
    if let Some(arch) = options.target.and_then(super::arch::Arch::from_target) {
        return arch.kind();
    }
    options
        .inputs
        .iter()
        .find_map(|input| match &input.kind {
            crate::args::InputKind::File(path) => sniff_file(path),
            crate::args::InputKind::Bytes { data, .. } => sniff_bytes(data),
            _ => None,
        })
        .or_else(|| {
            super::arch::Arch::from_target(super::target::default_target())
                .map(super::arch::Arch::kind)
        })
        .unwrap_or(ElfKind::Elf64Le)
}

/// The ELF kind of `data`: an ELF file's (a GCC LTO object's included) or
/// the one LLVM bitcode's triple names, or its first such member's if it is
/// an archive.
fn sniff_bytes(data: &[u8]) -> Option<ElfKind> {
    let one = |data: &[u8]| {
        // `EM_NONE` objects (`-b binary` inputs) name no target.
        let neutral = data.get(18..20) == Some(&[0, 0]);
        let elf = ElfKind::identify(data).filter(|_| !neutral);
        elf.or_else(|| {
            super::target::of_bitcode(data)
                .and_then(super::arch::Arch::from_target)
                .map(super::arch::Arch::kind)
        })
    };
    if let Some(kind) = one(data) {
        return Some(kind);
    }
    let archive = crate::input::archive::Archive::parse(std::path::Path::new(""), data).ok()?;
    archive
        .members()
        .filter_map(core::result::Result::ok)
        .find_map(|member| member.bytes().and_then(one))
}

/// [`sniff_bytes`] for a file on disk, reading as little of it as it can.
fn sniff_file(path: &std::path::Path) -> Option<ElfKind> {
    use std::io::Read;
    let mut file = std::fs::File::open(path).ok()?;
    let mut head = [0u8; 8];
    file.read_exact(&mut head).ok()?;
    if let Some(kind) = ElfKind::identify(&head) {
        return Some(kind);
    }
    let bitcode =
        head.starts_with(b"BC\xc0\xde") || head.starts_with(&0x0b17_c0de_u32.to_le_bytes());
    if &head != b"!<arch>\n" && !bitcode {
        return None;
    }
    // An archive or bitcode: read it whole.
    let data = std::fs::read(path).ok()?;
    sniff_bytes(&data)
}

fn link_as<F: crate::elf::read::ElfFormat>(
    prepared: &super::script_layout::Prepared,
    diagnostics: &dyn DiagnosticSink,
) -> Result<()> {
    let options = &prepared.options;
    // The DWARF the indexes are built from is read little-endian only.
    if <F::Endian as crate::elf::read::Endian>::ENDIANNESS == crate::target::Endianness::Big
        && (options.gdb_index || options.debug_names)
    {
        return Err(Error::Unimplemented(
            "--gdb-index and --debug-names for big-endian output".into(),
        ));
    }
    if options.kind == crate::args::OutputKind::Relocatable && F::KIND != ElfKind::Elf64Le {
        // `relocatable` writes 64-bit records, and has no `SHT_REL` output.
        return Err(Error::Unimplemented(format!(
            "relocatable output (-r) for {:?} (roadmap M4: more ELF architectures)",
            F::KIND
        )));
    }
    let timing = options.timing.as_ref();
    let start = Instant::now();
    let lap = |what: &str| {
        if let Some(timing) = timing {
            timing.write_line(&format!(
                "qld: {what}: {:.1} ms",
                start.elapsed().as_secs_f64() * 1000.0
            ));
        }
    };

    let wrap = WrapTable::new(&options.wrap);
    let mut internal = InternalNames::new(options);
    prepared.add_internal_names(&mut internal.names);
    let mut script = prepared.script.as_ref();
    let table = FileTable::for_link(options);
    let config = ParseConfig {
        strip_debug: options.strip >= StripMode::Debug,
        wrap: &wrap,
        table: &table,
    };
    // Running inside a pool the caller installed, without `--threads`:
    // that pool is the caller's to size, so the link uses it as it is and
    // builds none of its own. `--threads` means the pool around this call
    // is one qld built for this link (see `crate::link`), which qld may
    // narrow.
    let caller_pool = options.threads.is_none() && rayon::current_thread_index().is_some();
    // Without `--threads` and outside a caller's pool, the link runs in
    // pools of its own and never starts rayon's global pool (one thread per
    // core): mapping the inputs gains nothing from more than a few threads,
    // and 849 objects took 50 ms on 64 threads against 10 ms on 16.
    let own_pools = options.threads.is_none() && !caller_pool;
    // With `--threads` above MAX_DEFAULT_THREADS, the stages that get
    // slower with more threads run in a pool of MAX_DEFAULT_THREADS; see
    // `Narrow`.
    let mut narrow = Narrow {
        pool: (options.threads.is_some() && rayon::current_num_threads() > MAX_DEFAULT_THREADS)
            .then(|| thread_pool(MAX_DEFAULT_THREADS))
            .transpose()?,
        widen: None,
    };
    let mut inputs = if own_pools {
        let threads = available_threads().min(INPUT_THREADS);
        thread_pool(threads)?
            .install(|| inputs::collect::<F>(options, &table, &internal, config))?
    } else {
        narrow.run(|| inputs::collect::<F>(options, &table, &internal, config))?
    };
    lap("inputs");
    // x86-64 relocatable output follows GNU ld's built-in `-r` layout.
    if let Some(default) = &prepared.relocatable_default
        && super::arch::Arch::of(options, &inputs.files) == super::arch::Arch::X86_64
    {
        script = Some(default);
    }
    options.check_cancelled()?;

    let threads = input_sized_threads::<F>(options, &table, own_pools);
    if own_pools
        && threads == Some(MAX_DEFAULT_THREADS)
        && available_threads() > MAX_DEFAULT_THREADS
    {
        narrow.widen = Some(available_threads());
    }
    match threads {
        Some(threads) => thread_pool(threads)?.install(|| {
            link_inputs(
                options,
                diagnostics,
                &mut inputs,
                &internal,
                script,
                &lap,
                &narrow,
            )
        }),
        None => link_inputs(
            options,
            diagnostics,
            &mut inputs,
            &internal,
            script,
            &lap,
            &narrow,
        ),
    }
}

/// A pool of [`MAX_DEFAULT_THREADS`] threads for the stages that do not
/// scale past it, when `--threads` asked for a larger pool; `None`
/// otherwise, including in a pool the caller installed, which is the
/// caller's to size.
///
/// Past 16 threads, most stages get slower on the 32-core development
/// machine, not faster: idle rayon workers spin looking for work between
/// the many short parallel steps, share cores with the busy ones, and page
/// faults and `mmap` contend in the kernel. Measured at 16 and 64 threads
/// (clang, `libclang-cpp`, clang with debug information): mapping the
/// inputs took 5 ms against 28-53 ms (1,014 objects), resolution 50
/// against 62 ms, the dynamic symbol plan 15 against 24 ms, layout 9
/// against 15 ms, and the write of a 1.2 GiB output 353 against 451 ms.
/// The relocation scan and section merging still gain from the larger pool
/// (merging clang's 18 million debug strings: 182 ms on 16 threads, 153 on
/// 64), so they keep it. With this, `--threads=64` links as fast as 16
/// threads or faster: clang 155 ms against 203 before, clang with debug
/// information 670 against 771, `libclang-cpp` 121 against 189.
///
/// The other way round, a large link in qld's own pool of 16 threads merges
/// sections in a pool of one thread per core when there are many pieces
/// (`widen`, see [`merge::merge`]).
struct Narrow {
    pool: Option<rayon::ThreadPool>,
    /// Threads for section merging, when they are more than the link's.
    widen: Option<usize>,
}

impl Narrow {
    /// Runs `op` in the narrow pool, if there is one.
    fn run<R: Send>(&self, op: impl FnOnce() -> R + Send) -> R {
        match &self.pool {
            Some(pool) => pool.install(op),
            None => op(),
        }
    }
}

/// Threads used to map and index the inputs when `--threads` is not given.
const INPUT_THREADS: usize = 16;

/// The number of threads this process may run: the available parallelism.
fn available_threads() -> usize {
    std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
}

/// A rayon pool of `threads` threads.
fn thread_pool(threads: usize) -> Result<rayon::ThreadPool> {
    rayon::ThreadPoolBuilder::new()
        .num_threads(threads)
        .build()
        .map_err(|e| Error::Internal(format!("cannot create thread pool: {e}")))
}

/// Rejects options whose effect is not implemented yet, rather than
/// silently producing a different binary.
fn check_supported(options: &LinkOptions) -> Result<()> {
    let unimplemented = |what: &str, milestone: &str| {
        Err(Error::Unimplemented(format!(
            "{what} (roadmap {milestone})"
        )))
    };
    if let Some(format) = &options.output_format
        && !matches!(
            format.name(),
            "elf64-x86-64" | "elf64-x86_64" | "binary" | "ihex" | "srec"
        )
    {
        return unimplemented(&format!("--oformat {}", format.name()), "M4");
    }
    if options.kind == OutputKind::Relocatable
        && options.compress_debug_sections != crate::args::DebugCompression::None
    {
        return unimplemented("--compress-debug-sections with -r", "M5");
    }
    if options.kind == OutputKind::Relocatable {
        if options.gdb_index {
            return Err(Error::Option(
                "-r and --gdb-index may not be used together".into(),
            ));
        }
        if options.debug_names {
            return Err(Error::Option(
                "-r and --debug-names may not be used together".into(),
            ));
        }
        if options.symbol_ordering_file.is_some()
            || options.call_graph_ordering_file.is_some()
            || options
                .call_graph_profile_sort
                .is_some_and(|s| s != crate::args::options::CallGraphSort::None)
        {
            return unimplemented("section ordering with -r", "M5");
        }
    }
    if options.separate_debug_file.is_some()
        && (options.kind == OutputKind::Relocatable
            || options
                .output_format
                .as_ref()
                .is_some_and(crate::args::OutputFormat::is_raw))
    {
        return Err(Error::Option(
            "--separate-debug-file needs an ELF executable or shared object output".into(),
        ));
    }
    for (name, expr) in &options.defsym {
        defined::defsym_assignment(name, expr)?;
    }
    Ok(())
}

/// Input bytes per worker thread when `--threads` is not given.
const BYTES_PER_THREAD: u64 = 4 << 20;
/// Most threads used when `--threads` is not given.
const MAX_DEFAULT_THREADS: usize = 16;

/// The thread count for a link whose thread count was not set explicitly:
/// one thread per [`BYTES_PER_THREAD`] of input, at most
/// [`MAX_DEFAULT_THREADS`] and the available parallelism. `None` keeps the
/// current pool, which is what a link inside a caller's pool always gets:
/// that pool is the caller's to size.
///
/// Small links are dominated by the fixed cost of spreading tiny tasks over
/// many threads (a static "hello world" takes 10 ms on one thread and 28 ms
/// on 64). The output does not depend on the thread count.
fn input_sized_threads<F: crate::elf::read::ElfFormat>(
    options: &LinkOptions,
    table: &FileTable,
    own_pools: bool,
) -> Option<usize> {
    if options.threads.is_some() {
        return None;
    }
    let top_level = || table.iter().filter(|(_, file)| file.parent().is_none());
    let mut bytes: u64 = top_level()
        .map(|(_, file)| u64::try_from(file.data().len()).unwrap_or(u64::MAX))
        .fold(0u64, u64::saturating_add);
    // Compressed debug sections count at their uncompressed size: inflating
    // them and writing them out is the work (256 objects whose 320 MiB of
    // debug information compress to under a megabyte linked on one thread).
    // Only links that would get fewer than the most threads look, and only
    // at section headers.
    let most = BYTES_PER_THREAD.saturating_mul(MAX_DEFAULT_THREADS as u64);
    if bytes < most {
        for (_, file) in top_level() {
            bytes = bytes.saturating_add(compressed_growth::<F>(file));
            if bytes >= most {
                break;
            }
        }
    }
    let wanted = usize::try_from(bytes.div_ceil(BYTES_PER_THREAD))
        .unwrap_or(usize::MAX)
        .clamp(1, MAX_DEFAULT_THREADS);
    own_pools.then(|| wanted.min(available_threads()))
}

/// How many bytes the compressed sections of a relocatable ELF input grow
/// by when inflated (0 for anything else, and for malformed files, which
/// parsing reports later).
fn compressed_growth<F: crate::elf::read::ElfFormat>(file: &crate::input::InputFile) -> u64 {
    use crate::elf::read::{ObjectFile, Source};
    use crate::input::FileFormat;
    if !matches!(file.format(), FileFormat::Elf(ident) if ident.is_relocatable()) {
        return 0;
    }
    let Ok(object) = ObjectFile::<F>::parse(file.data(), Source::new(file.path())) else {
        return 0;
    };
    object
        .elf()
        .sections()
        .iter()
        .filter(|header| header.is_compressed())
        .filter_map(|header| {
            let (chdr, _) = object.compressed_data(&header).ok()??;
            Some(chdr.ch_size.saturating_sub(header.sh_size))
        })
        .fold(0u64, u64::saturating_add)
}

/// Everything after input collection, run in the link's thread pool.
#[allow(clippy::too_many_lines)]
fn link_inputs<'a, F: crate::elf::read::ElfFormat>(
    options: &LinkOptions,
    diagnostics: &'a dyn DiagnosticSink,
    inputs: &mut inputs::Inputs<'a, F>,
    internal: &InternalNames,
    script: Option<&'a super::script_layout::LayoutScript>,
    lap: &(dyn Fn(&str) + Sync),
    narrow: &Narrow,
) -> Result<()> {
    let rules = ElfRules {
        allow_multiple_definition: options.allow_multiple_definition,
    };
    // Resolution, and LTO when a plugin claims IR inputs (`lto` module).
    let (mut symbols, resolution, lto) =
        narrow.run(|| super::lto::resolve(options, diagnostics, &rules, inputs))?;
    let files = &inputs.files;
    narrow.run(|| dso::bind_unextracted(files, &symbols, &resolution));
    lap("resolution");
    options.check_cancelled()?;

    let mut sections = narrow.run(|| Sections::new(files, &resolution))?;
    let relocatable = options.kind == OutputKind::Relocatable;
    if relocatable {
        relocatable::revive_sections(files, &mut sections, options);
    } else if options.emit_relocs {
        // GNU ld keeps `.note.GNU-stack` as an output section with -q.
        relocatable::revive_named(files, &mut sections, b".note.GNU-stack");
    }
    if options
        .output_format
        .as_ref()
        .is_some_and(crate::args::OutputFormat::is_raw)
    {
        // Raw formats link through BFD's generic linker, which copies
        // property notes rather than merging them.
        relocatable::revive_named(files, &mut sections, b".note.gnu.property");
    }
    let (mut errors, cref) = narrow.run(|| {
        resolve::deduplicate_comdat(files, &mut sections);
        let errors = resolve::report_duplicates(
            files,
            &resolution,
            &sections,
            options.demangle,
            diagnostics,
        );
        report_gnu_warnings(files, &symbols, diagnostics);
        xref::trace_symbols(files, &resolution, options, diagnostics);
        xref::warn_common(files, &resolution, options, diagnostics);
        let cref = xref::cross_reference(files, &symbols, &resolution, options);
        (errors, cref)
    });

    if relocatable {
        if errors > 0 && !options.noinhibit_exec {
            return Err(Error::Reported { errors });
        }
        link_relocatable(
            options,
            diagnostics,
            files,
            &symbols,
            &resolution,
            sections,
            internal,
            script,
            lap,
        )?;
        map::write_cref(options, cref.as_deref())?;
        lto.finish(diagnostics)?;
        options.output_complete();
        return Ok(());
    }

    let mode = Mode::new(options, files.iter().any(|f| f.shared.is_some()));
    let rule_set = RuleSet::for_link(script, diagnostics, super::arch::Arch::of(options, files));
    // Which shared objects the output needs and where input sections go are
    // independent passes; neither keeps every thread busy.
    let (needed, mut placement) = narrow.run(|| {
        rayon::join(
            || dso::plan_needed(files, &symbols, &rules, &resolution),
            || place::place(&rule_set, files, &sections, options),
        )
    });
    if mode.dynamic && !mode.shared {
        narrow.run(|| dso::mark_dependency_symbols(files, &symbols, &needed, options));
    }
    let always = defined::always_defined(mode, script.is_some(), files);
    for name in &always {
        symbols.intern(SymbolName::new(name.as_bytes()));
    }
    let always = always.as_slice();

    for id in &placement.discarded {
        if let Some(slot) = sections.live.get_mut(id.index()) {
            *slot = false;
        }
    }
    let linker = narrow
        .run(|| defined::register(&symbols, files, &placement, options, mode.dynamic, always));
    let (mut version_script, dynamic_patterns) = export::read_scripts(options)?;
    if version_script.is_none()
        && let Some(nodes) = script.map(|s| &s.version).filter(|v| !v.is_empty())
    {
        version_script = Some(export::VersionScript::new(nodes)?);
    }
    let exports = narrow.run(|| {
        export::plan(
            files,
            &symbols,
            &resolution,
            &needed,
            options,
            mode,
            version_script,
            &dynamic_patterns,
            &linker,
        )
    })?;
    lap("placement");
    options.check_cancelled()?;

    // `--gc-sections` needs the `.eh_frame` records to follow the graph, so
    // they are split here; without it the split runs beside the relocation
    // scan (below), which needs nothing from it.
    let mut eh_frames = if options.gc_sections {
        Some(narrow.run(|| ehframe::split(files, &sections))?)
    } else {
        None
    };
    if let Some(eh_frames) = eh_frames.as_mut() {
        let refs = Refs {
            files,
            symbols: &symbols,
            resolution: &resolution,
            sections: &sections,
        };
        let why_live = !options.why_live.is_empty();
        let (removed, graph) = narrow
            .run(|| gc::collect(&refs, &placement, eh_frames, &linker, internal, why_live))?;
        if options.print_gc_sections {
            gc::print_removed(&refs, &removed, diagnostics);
        }
        if let Some(graph) = &graph {
            gc::report_why_live(&refs, graph, &options.why_live, diagnostics);
        }
        for id in &removed {
            if let Some(slot) = sections.live.get_mut(id.index()) {
                *slot = false;
            }
        }
        eh_frames
            .sections
            .retain(|s| sections.live.get(s.id.index()).copied().unwrap_or(false));
        narrow.run(|| placement.compute_flags(files, &sections));
        lap("gc");
        options.check_cancelled()?;
    }

    let refs = Refs {
        files,
        symbols: &symbols,
        resolution: &resolution,
        sections: &sections,
    };
    let arch = super::arch::Arch::of(options, files);
    if arch.kind() != F::KIND {
        // x32 (ELF32 x86-64) and the other ELF32 or big-endian variants of
        // a 64-bit architecture.
        return Err(Error::Unimplemented(format!(
            "linking {:?} objects for {} (roadmap M4: more ELF architectures)",
            F::KIND,
            arch.emulation()
        )));
    }
    let context = reloc::Context {
        mode,
        relax: options.relax,
        copy_relocs: options.copy_relocs,
        arch,
        weak_zero: reloc::Context::weak_zero(arch, mode),
    };
    // Section merging needs neither the scan's results nor anything it
    // changes (symbol flags), and neither stage keeps every thread busy on
    // its own: they run side by side. A merge error counts only if the scan
    // reports none, as when the merge ran after it.
    // The debug indexes only read the inputs: they are built alongside.
    let ((scan, split), (merged, debug_indexes)) = rayon::join(
        || {
            rayon::join(
                || scan::scan(&refs, &context),
                || match eh_frames {
                    Some(eh_frames) => Ok(eh_frames),
                    None => ehframe::split(files, &sections),
                },
            )
        },
        || {
            rayon::join(
                || {
                    merge::merge(
                        files,
                        &sections,
                        &placement,
                        options.optimize >= 2,
                        narrow.widen,
                    )
                },
                || {
                    crate::debug::gdb_index::elf::DebugIndexes::build(
                        files,
                        &resolution,
                        &sections,
                        options,
                    )
                },
            )
        },
    );
    let mut eh_frames = split?;
    for file in &scan.files {
        for error in &file.errors {
            diagnostics.emit(error.clone());
            errors = errors.saturating_add(1);
        }
    }
    errors = errors.saturating_add(report_undefined(
        &refs,
        &scan,
        options,
        mode,
        &needed,
        diagnostics,
    ));
    errors = errors.saturating_add(dso::check_shlib_undefined(
        files,
        &symbols,
        &resolution,
        &needed,
        options,
        diagnostics,
    ));
    if scan.text_relocs() && mode.dynamic {
        let message = if mode.shared {
            "creating DT_TEXTREL in a shared object"
        } else {
            "creating DT_TEXTREL in a PIE"
        };
        if options.error_textrel {
            diagnostics.emit(Diagnostic::error(message.to_string()));
            errors = errors.saturating_add(1);
        } else if options.warn_textrel || mode.pic {
            diagnostics.emit(Diagnostic::warning(message.to_string()));
        }
    }
    if errors > 0 && !options.noinhibit_exec {
        return Err(Error::Reported { errors });
    }
    lap("scan");
    options.check_cancelled()?;

    let commons = narrow.run(|| common::allocate(&refs));
    let merged = merged?;
    lap("merge");
    options.check_cancelled()?;
    let icf_mode = match options.icf {
        crate::args::IcfMode::All => Some(IcfMode::All),
        crate::args::IcfMode::Safe => Some(IcfMode::Safe),
        _ => None,
    };
    if let Some(icf_mode) = icf_mode {
        let fold_into = icf::fold(
            &refs,
            &placement,
            &merged,
            icf_mode,
            context.arch,
            options.print_icf_sections,
            diagnostics,
        )?;
        sections.apply_folding(fold_into);
        lap("icf");
        options.check_cancelled()?;
    }
    let mut debug_indexes = debug_indexes?;
    debug_indexes.apply(files, &resolution, &mut sections, diagnostics);
    let refs = Refs {
        files,
        symbols: &symbols,
        resolution: &resolution,
        sections: &sections,
    };
    let order = super::ordering::for_link(&refs, &placement, options, diagnostics)?;

    let mut synth = Synth {
        arch: context.arch,
        bind_now: options.bind_now,
        ..Synth::default()
    };
    // The live `.eh_frame` records, the GOT/PLT entries and the non-empty
    // output sections are three independent passes over the inputs, and
    // none of them keeps every thread busy on its own: they run side by
    // side.
    let nonempty_outputs = narrow.run(|| {
        let (nonempty, ()) = rayon::join(
            || {
                synth.plan_entries(&refs, &scan, mode);
                nonempty_outputs(files, &sections, &placement)
            },
            || eh_frames.finalize(&refs),
        );
        nonempty
    });
    narrow.run(|| synth.plan_entries(&refs, &scan, mode));
    if context.arch == super::arch::Arch::Arm {
        // Entries that repeat the one before are dropped only when the
        // order the exception index is planned in is the one layout will
        // place the code in.
        let default_order = script.is_none() && order.as_ref().is_none_or(|o| o.is_empty());
        synth.arm = Some(Box::new(super::arch::arm::prepare(
            &refs,
            &placement,
            default_order && options.merge_exidx_entries,
        )));
    }
    // DT_RELR is for position-independent output; GNU ld ignores the
    // option otherwise.
    synth.relr = options.pack_relative_relocs && mode.pic;
    synth.relr_size = synth
        .relr_count()
        .div_ceil(32)
        .saturating_add(8)
        .saturating_mul(context.arch.kind().word_size());
    synth.ibt = synth::plan_ibt(files, options);
    synth.pac_plt = synth::plan_pac_plt(files, options);
    for warning in synth::force_bti_warnings(files, options) {
        diagnostics.emit(warning);
    }
    synth.build_id = synth::plan_build_id(options);
    synth.property_note = synth::plan_property_note(files, options);
    synth.interp = synth::plan_interp(options, mode, context.arch);
    synth.fde_count = u64::try_from(eh_frames.live_fdes()).unwrap_or(0);
    synth.eh_frame_hdr = options.eh_frame_hdr && synth.fde_count > 0;
    synth.eh_frame_end = eh_frames.sections.iter().any(|s| s.size > 0);
    synth.common = (commons.size, commons.align);

    let has_output = |name: &[u8]| {
        placement
            .outputs
            .iter()
            .zip(&nonempty_outputs)
            .any(|(output, &nonempty)| nonempty && output.name == name)
    };
    let soname = options
        .soname
        .as_ref()
        .map(|s| s.as_bytes().to_vec())
        .or_else(|| {
            options
                .output_path()
                .file_name()
                .map(|n| n.as_encoded_bytes().to_vec())
        });
    let input = dynsym::PlanInput {
        refs: &refs,
        needed: &needed,
        mode,
        options,
        synth: &synth,
        exports: &exports,
        scan: &scan,
        has_output: &has_output,
        soname,
    };
    // Choosing the dynamic symbols sets reference flags on strong aliases
    // of weak imports (`environ`), which the symbol table plan reads, so it
    // comes first; the rest of the dynamic plan changes nothing the symbol
    // table plan reads, and the two run side by side.
    let chosen = narrow.run(|| dynsym::choose(&input));
    let (dynamic, plan) = narrow.run(|| {
        rayon::join(
            || dynsym::plan_chosen(&input, chosen),
            || symtab::plan(&refs, &linker, options, context.arch.kind()),
        )
    });
    let dynamic = dynamic?;
    synth.dynamic_sizes = dynamic.sizes();
    synth.verneed_count = dynamic.verneed_count;
    synth.verdef_count = dynamic.verdef_count;
    lap("dynamic");
    options.check_cancelled()?;

    let mut trailers = TrailerSizes {
        symtab: plan.symtab_size(),
        strtab: if plan.is_empty() {
            0
        } else {
            u64::try_from(plan.strtab_size).unwrap_or(u64::MAX)
        },
        first_global: u32::try_from(plan.first_global).unwrap_or(0),
        debug_names: debug_indexes.debug_names_size(),
        gdb_index: debug_indexes.gdb_index_size(),
        ..TrailerSizes::default()
    };
    let exec_stack = files
        .iter()
        .filter_map(|f| f.object.as_ref())
        .any(|o| o.exec_stack);
    let mut layout = narrow.run(|| {
        layout::layout(&LayoutInput {
            options,
            refs,
            rules: &rule_set,
            files,
            sections: &sections,
            placement: &placement,
            merged: &merged,
            eh_frames: &eh_frames,
            synth: &synth,
            trailers,
            exec_stack,
            mode,
            compressed: &[],
            order: order.as_ref(),
            relax: None,
        })
    })?;
    // `.relr.dyn`'s size depends on the addresses it encodes: lay out with an
    // estimate, and again with the real size while it does not fit (growth
    // rarely moves anything, as the next segment starts on a page boundary).
    let mut relr = Vec::new();
    if synth.relr_count() > 0 {
        // Shrinking to the exact size is tried once; after that a smaller
        // encoding is padded with empty bitmaps.
        let mut shrunk = false;
        for attempt in 0..8 {
            let addresses = Addresses::new(
                refs, &layout, &merged, &eh_frames, &synth, &commons, &placement, &linker, options,
            );
            let places = write::relr_addresses(&addresses, &context, &dynamic, &scan);
            relr = write::encode_relr(&places, context.arch.kind());
            let size = u64::try_from(relr.len())
                .unwrap_or(u64::MAX)
                .saturating_mul(context.arch.kind().word_size());
            if size == synth.relr_size || (size < synth.relr_size && shrunk) {
                break;
            }
            if attempt == 7 {
                if size <= synth.relr_size {
                    break;
                }
                return Err(Error::Internal(".relr.dyn size did not converge".into()));
            }
            shrunk |= size < synth.relr_size;
            synth.relr_size = size;
            layout = layout::layout(&LayoutInput {
                options,
                refs,
                rules: &rule_set,
                files,
                sections: &sections,
                placement: &placement,
                merged: &merged,
                eh_frames: &eh_frames,
                synth: &synth,
                trailers,
                exec_stack,
                mode,
                compressed: &[],
                order: order.as_ref(),
                relax: None,
            })?;
        }
    }
    lap("layout");
    options.check_cancelled()?;

    let mut plan = plan;
    plan.add_section_symbols(layout.section_symbols as usize);
    let tombstones = Tombstones::new(TombstoneStyle::Lld)
        .with_rules(
            options
                .dead_reloc_in_nonalloc
                .iter()
                .map(|(glob, value)| (glob.as_bytes(), *value)),
        )
        .map_err(|e| Error::Option(e.0))?;

    // --compress-debug-sections: render and compress the debug sections
    // with the final addresses, then lay out again with their new sizes
    // (they follow every allocated section, so no address moves).
    let compression = {
        let level = if options.optimize >= 2 {
            crate::debug::compress::deflate::Level::DEFAULT
        } else {
            crate::debug::compress::deflate::Level::FASTEST
        };
        crate::debug::section::OutputCompression::from_option(
            options.compress_debug_sections,
            level,
        )
    };
    let mut prerendered = Vec::new();
    if let Some(compression) = compression {
        let addresses = Addresses::new(
            refs, &layout, &merged, &eh_frames, &synth, &commons, &placement, &linker, options,
        );
        prerendered = write::prerender_debug_sections(
            &WriteInput {
                options,
                addresses: &addresses,
                symtab: &plan,
                linker: &linker,
                dynamic: &dynamic,
                scan: &scan,
                context,
                tombstones: &tombstones,
                relr: &relr,
                entry: 0,
                prerendered: &[],
                diagnostics,
            },
            compression,
        )?;
        let sizes: Vec<layout::CompressedOutput> = prerendered
            .iter()
            .filter(|p| p.compressed)
            .filter_map(|p| {
                let section = layout.sections.get(p.position as usize)?;
                Some(layout::CompressedOutput {
                    output: section.output,
                    size: u64::try_from(p.bytes.len()).ok()?,
                    gnu: !compression.is_gabi(),
                })
            })
            .collect();
        // The merged `.debug_names` is compressed too.
        if let Some(gnu) = debug_indexes.compress(&addresses, compression)? {
            trailers.debug_names = debug_indexes.debug_names_size();
            trailers.debug_names_compressed = Some(gnu);
        }
        drop(addresses);
        if !sizes.is_empty() || trailers.debug_names_compressed.is_some() {
            layout = layout::layout(&LayoutInput {
                options,
                refs,
                rules: &rule_set,
                files,
                sections: &sections,
                placement: &placement,
                merged: &merged,
                eh_frames: &eh_frames,
                synth: &synth,
                trailers,
                exec_stack,
                mode,
                compressed: &sizes,
                order: order.as_ref(),
                relax: None,
            })?;
        }
        lap("compress");
        options.check_cancelled()?;
    }

    let addresses = narrow.run(|| {
        Addresses::new(
            refs, &layout, &merged, &eh_frames, &synth, &commons, &placement, &linker, options,
        )
    });
    let entry = entry_address(&addresses, options, mode, diagnostics);
    narrow.run(|| debug_indexes.render(&addresses, &mut prerendered))?;
    let debug_path = super::separate_debug::debug_path(options);
    if let Some(debug_path) = &debug_path {
        // `--separate-debug-file`: the output is laid out again without
        // the debug sections (allocated sections do not move), written,
        // and the complete layout becomes the debug file's.
        narrow.run(|| map::write(options, &addresses, &plan, cref.as_deref()))?;
        drop(addresses);
        let stripped = super::separate_debug::stripped_sections(&sections, &placement);
        let stripped_refs = Refs {
            sections: &stripped,
            ..refs
        };
        let main_layout = narrow.run(|| {
            layout::layout(&LayoutInput {
                options,
                refs: stripped_refs,
                rules: &rule_set,
                files,
                sections: &stripped,
                placement: &placement,
                merged: &merged,
                eh_frames: &eh_frames,
                synth: &synth,
                trailers: TrailerSizes {
                    debuglink: super::separate_debug::debuglink_size(debug_path),
                    ..TrailerSizes::default()
                },
                exec_stack,
                mode,
                compressed: &[],
                order: order.as_ref(),
                relax: None,
            })
        })?;
        let link = main_layout
            .sections
            .iter()
            .position(|s| s.name == b".gnu_debuglink")
            .and_then(|p| u32::try_from(p).ok())
            .map(|position| write::Prerendered {
                position,
                bytes: super::separate_debug::debuglink_contents(debug_path),
                compressed: false,
            });
        let main_addresses = Addresses::new(
            stripped_refs,
            &main_layout,
            &merged,
            &eh_frames,
            &synth,
            &commons,
            &placement,
            &linker,
            options,
        );
        narrow.run(|| {
            write::write(&WriteInput {
                options,
                addresses: &main_addresses,
                symtab: &plan,
                linker: &linker,
                dynamic: &dynamic,
                scan: &scan,
                context,
                tombstones: &tombstones,
                relr: &relr,
                entry,
                prerendered: link.as_slice(),
                diagnostics,
            })
        })?;
        let (crc, build_id) = super::separate_debug::finish_output::<F>(
            &options.output_path(),
            &main_layout,
            options,
        )?;
        drop(main_addresses);
        super::separate_debug::to_debug_file(&mut layout)?;
        let mut debug_options = options.clone();
        debug_options.output = Some(debug_path.clone());
        debug_options.build_id = crate::args::BuildId::None;
        let debug_addresses = Addresses::new(
            refs,
            &layout,
            &merged,
            &eh_frames,
            &synth,
            &commons,
            &placement,
            &linker,
            &debug_options,
        );
        narrow.run(|| {
            write::write(&WriteInput {
                options: &debug_options,
                addresses: &debug_addresses,
                symtab: &plan,
                linker: &linker,
                dynamic: &dynamic,
                scan: &scan,
                context,
                tombstones: &tombstones,
                relr: &relr,
                entry,
                prerendered: &prerendered,
                diagnostics,
            })
        })?;
        super::separate_debug::finish_debug_file(debug_path, &layout, build_id.as_deref(), crc)?;
    } else {
        narrow.run(|| {
            write::write(&WriteInput {
                options,
                addresses: &addresses,
                symtab: &plan,
                linker: &linker,
                dynamic: &dynamic,
                scan: &scan,
                context,
                tombstones: &tombstones,
                relr: &relr,
                entry,
                prerendered: &prerendered,
                diagnostics,
            })
        })?;
        narrow.run(|| map::write(options, &addresses, &plan, cref.as_deref()))?;
    }
    lap("write");
    lto.finish(diagnostics)?;
    // Freeing the link's data and unmapping the inputs come after this.
    options.output_complete();
    Ok(())
}

/// The rest of a relocatable (`-r`) link: `--gc-sections` when asked (GNU
/// ld requires `-e` or `-u` roots for it), then [`relocatable::write`].
#[allow(clippy::too_many_arguments)]
fn link_relocatable<'a, F: crate::elf::read::ElfFormat>(
    options: &LinkOptions,
    diagnostics: &dyn DiagnosticSink,
    files: &[inputs::ElfInput<'a, F>],
    symbols: &SymbolTable<'a>,
    resolution: &crate::symbols::Resolution<'a>,
    mut sections: Sections,
    internal: &InternalNames,
    script: Option<&'a super::script_layout::LayoutScript>,
    lap: &(dyn Fn(&str) + Sync),
) -> Result<()> {
    // A linker script places sections (`/DISCARD/` removes them) before
    // garbage collection, whose `KEEP` roots it gives.
    let script_placement =
        script.map(|s| super::script_layout::relocatable::place(s, files, &mut sections, options));
    if script.is_some() {
        lap("script placement");
    }
    if options.gc_sections {
        if options.entry.is_none() && options.undefined.is_empty() {
            return Err(Error::Option(
                "--gc-sections requires a defined symbol root specified by -e or -u".into(),
            ));
        }
        let rule_set = RuleSet::default_rules_for(super::arch::Arch::of(options, files));
        let default_placement;
        let placement = match &script_placement {
            Some(placement) => placement,
            None => {
                default_placement = place::place(&rule_set, files, &sections, options);
                &default_placement
            }
        };
        let eh_frames = ehframe::split(files, &sections)?;
        let refs = Refs {
            files,
            symbols,
            resolution,
            sections: &sections,
        };
        let linker = defined::LinkerSymbols::default();
        let why_live = !options.why_live.is_empty();
        let (removed, graph) =
            gc::collect(&refs, placement, &eh_frames, &linker, internal, why_live)?;
        if options.print_gc_sections {
            gc::print_removed(&refs, &removed, diagnostics);
        }
        if let Some(graph) = &graph {
            gc::report_why_live(&refs, graph, &options.why_live, diagnostics);
        }
        for &id in &removed {
            // Sections only relocatable output copies (`.note.GNU-stack`,
            // non-allocated `SHF_EXCLUDE` sections) are not layout rules'
            // roots, but GNU ld keeps them.
            let consumed = sections
                .locate(id)
                .and_then(|(file, index)| files.get(file)?.object.as_ref()?.section(index))
                .is_some_and(|s| s.kind == SectionKind::Ignored && !s.is_alloc());
            if !consumed && let Some(slot) = sections.live.get_mut(id.index()) {
                *slot = false;
            }
        }
        lap("gc");
        options.check_cancelled()?;
    }
    let refs = Refs {
        files,
        symbols,
        resolution,
        sections: &sections,
    };
    let commons = options.define_common.then(|| common::allocate(&refs));
    let script_layout = match (script, &script_placement) {
        (Some(script), Some(placement)) => Some(super::script_layout::relocatable::layout(
            script, placement, files, &sections, symbols, options,
        )?),
        _ => None,
    };
    if script_layout.is_some() {
        lap("script layout");
    }
    relocatable::write(&relocatable::RelocatableInput {
        options,
        refs,
        commons: commons.as_ref(),
        script: script_layout.as_ref(),
    })?;
    lap("write");
    Ok(())
}

/// Whether each placement output receives a non-empty live input section.
fn nonempty_outputs<F: crate::elf::read::ElfFormat>(
    files: &[super::inputs::ElfInput<'_, F>],
    sections: &Sections,
    placement: &place::Placement<'_>,
) -> Vec<bool> {
    let outputs = placement.outputs.len();
    // Per file in parallel (a bit set per file would be as large as the
    // output list, so each file lists what it fills), then combined.
    let filled: Vec<Vec<u32>> = files
        .par_iter()
        .enumerate()
        .map(|(file_index, file)| {
            let mut filled = Vec::new();
            let Some(object) = &file.object else {
                return filled;
            };
            for (index, section) in object.sections.iter().enumerate() {
                let Some(id) = sections.id(file_index, u32::try_from(index).unwrap_or(u32::MAX))
                else {
                    continue;
                };
                if section.header.sh_size == 0 || !sections.is_live(id) {
                    continue;
                }
                if let Some(output) = placement.output_of(id)
                    && filled.last() != Some(&output)
                {
                    filled.push(output);
                }
            }
            filled
        })
        .collect();
    let mut nonempty = vec![false; outputs];
    for output in filled.into_iter().flatten() {
        if let Some(slot) = nonempty.get_mut(output as usize) {
            *slot = true;
        }
    }
    nonempty
}

/// A symbol name for diagnostics: demangled when `demangle` is set, with
/// its `@VERSION`.
fn symbol_display(name: SymbolName<'_>, demangle: bool) -> String {
    let base = crate::hints::display_symbol(name.bytes(), demangle);
    match name.version() {
        Some(version) => format!("{base}@{}", String::from_utf8_lossy(version)),
        None => base.into_owned(),
    }
}

/// Library and near-miss hints ([`crate::hints`]) for each group of
/// undefined references. Runs only when a link has undefined symbols.
fn undefined_hints<F: crate::elf::read::ElfFormat>(
    refs: &Refs<'_, '_, F>,
    groups: &[&[UndefinedRef]],
    options: &LinkOptions,
    needed: &dso::Needed,
) -> Vec<Vec<crate::hints::Hint>> {
    use crate::hints::{Hinter, LinkedLibrary, SearchScope, Undefined};
    let mut linked: Vec<LinkedLibrary> = Vec::new();
    for (index, file) in refs.files.iter().enumerate() {
        let library = match file.role {
            inputs::InputRole::Shared => LinkedLibrary {
                path: file.path(),
                dropped_as_needed: !needed.is_needed(index),
                static_only: false,
            },
            inputs::InputRole::Member => LinkedLibrary::new(file.path()),
            _ => continue,
        };
        if !linked.iter().any(|l| l.path == library.path) {
            linked.push(library);
        }
    }
    let undefined: Vec<Undefined<'_>> = groups
        .iter()
        .filter_map(|g| g.first())
        .map(|r| {
            let name = refs.symbols.name(r.symbol);
            match name.version() {
                Some(version) => Undefined::versioned(name.bytes(), version),
                None => Undefined::new(name.bytes()),
            }
        })
        .collect();
    let defined: Vec<&[u8]> = refs
        .symbols
        .ids()
        .filter(|&id| {
            matches!(
                refs.symbols.definition_kind(id),
                crate::symbols::DefinitionKind::Regular
                    | crate::symbols::DefinitionKind::Weak
                    | crate::symbols::DefinitionKind::Common
                    | crate::symbols::DefinitionKind::Shared
            ) && refs.symbols.name(id).version().is_none()
        })
        .map(|id| refs.symbols.name(id).bytes())
        .collect();
    Hinter::new(SearchScope::from_options(options), linked).hints(&undefined, &defined)
}

/// Reports undefined symbols, lld-style. Returns the number of errors.
fn report_undefined<F: crate::elf::read::ElfFormat>(
    refs: &Refs<'_, '_, F>,
    scan: &scan::ScanResult,
    options: &LinkOptions,
    mode: Mode,
    needed: &dso::Needed,
    diagnostics: &dyn DiagnosticSink,
) -> usize {
    // A shared object may leave symbols for the dynamic linker to find,
    // unless `--no-undefined` or `-z defs`.
    if mode.shared && options.no_undefined != Some(true) {
        return 0;
    }
    let mut all: Vec<UndefinedRef> = scan
        .files
        .iter()
        .flat_map(|f| f.undefined.iter().copied())
        .collect();
    all.sort_unstable_by_key(|r| (r.symbol, r.file, r.section, r.offset));
    let mut errors = 0usize;
    let mut line_tables: std::collections::BTreeMap<
        usize,
        Option<crate::debug::dwarf::LineLookup>,
    > = std::collections::BTreeMap::new();
    let mut groups: Vec<&[UndefinedRef]> = all.chunk_by(|a, b| a.symbol == b.symbol).collect();
    groups.sort_by_key(|group| group.first().map(|r| (r.file, r.section, r.offset)));
    let ignore = matches!(
        options.unresolved_symbols,
        Some(
            crate::args::UnresolvedSymbols::IgnoreAll
                | crate::args::UnresolvedSymbols::IgnoreInObjectFiles
        )
    );
    // Symbols that a library's own dependency defines: that library is
    // missing from the command line.
    let names: Vec<&[u8]> = groups
        .iter()
        .filter_map(|g| g.first())
        .map(|r| refs.symbols.name(r.symbol).bytes())
        .collect();
    let in_dependencies = if names.is_empty() || ignore {
        Vec::new()
    } else {
        dso::defined_in_dependencies(refs.files, needed, options, &names)
    };
    let hints = if names.is_empty() || ignore {
        Vec::new()
    } else {
        undefined_hints(refs, &groups, options, needed)
    };
    for (group_index, group) in groups.into_iter().enumerate() {
        let Some(first) = group.first() else {
            continue;
        };
        let name = refs.symbols.name(first.symbol);
        if ignore
            || options
                .ignore_unresolved_symbols
                .iter()
                .any(|s| s.as_bytes() == name.bytes())
        {
            continue;
        }
        let order = refs.files.get(first.file).map_or(0, |f| f.position.raw());
        let shown = symbol_display(name, options.demangle);
        let mut diagnostic = if options.warn_unresolved_symbols {
            Diagnostic::warning(format!("undefined symbol: {shown}"))
        } else {
            Diagnostic::error(format!("undefined symbol: {shown}"))
        };
        diagnostic = diagnostic.order(order);
        for reference in group.iter().take(MAX_REFERENCES) {
            let mut location =
                scan::location(refs, reference.file, reference.section, reference.offset);
            // The source line, from the object's DWARF line table, parsed
            // once per file and only when an error is reported.
            let lookup = line_tables.entry(reference.file).or_insert_with(|| {
                refs.files
                    .get(reference.file)
                    .and_then(|f| f.object.as_ref())
                    .and_then(|o| crate::debug::dwarf::LineLookup::parse(&o.elf).ok())
            });
            if let Some(lookup) = lookup {
                location.source = lookup.find(reference.section, reference.offset);
            }
            diagnostic = diagnostic.at(location);
        }
        if group.len() > MAX_REFERENCES {
            diagnostic = diagnostic.note(format!(
                "referenced {} more times",
                group.len().saturating_sub(MAX_REFERENCES)
            ));
        }
        if let Some(Some((library, needed_by))) = in_dependencies.get(group_index) {
            diagnostic = diagnostic.note(format!(
                "'{shown}' is defined in {}, which {} needs but which is not in the link \
                 (DSO missing from command line); add it to the command line",
                library.display(),
                needed_by.display()
            ));
        }
        if let Some(hints) = hints.get(group_index) {
            diagnostic = crate::hints::attach(diagnostic, hints, options.demangle);
        }
        diagnostics.emit(diagnostic);
        if !options.warn_unresolved_symbols {
            errors = errors.saturating_add(1);
        }
    }
    for name in &options.require_defined {
        let defined = refs
            .symbols
            .lookup(&SymbolName::new(name.as_bytes()))
            .is_some_and(|id| !matches!(refs.global_target(id, false).def, Def::Undefined { .. }));
        if !defined {
            diagnostics.emit(Diagnostic::error(format!(
                "required symbol '{name}' is not defined"
            )));
            errors = errors.saturating_add(1);
        }
    }
    errors
}

/// Emits the messages of `.gnu.warning.SYM` sections whose symbol is
/// referenced (and of plain `.gnu.warning` sections), as GNU ld does.
fn report_gnu_warnings<F: crate::elf::read::ElfFormat>(
    files: &[super::inputs::ElfInput<'_, F>],
    symbols: &SymbolTable<'_>,
    diagnostics: &dyn DiagnosticSink,
) {
    for file in files {
        let Some(object) = &file.object else {
            continue;
        };
        for &index in &object.warnings {
            let Some(section) = object.section(index) else {
                continue;
            };
            let symbol = section.name.strip_prefix(b".gnu.warning.");
            let used = match symbol {
                Some(name) => symbols.lookup(&SymbolName::new(name)).is_some_and(|id| {
                    symbols
                        .flags(id)
                        .contains(crate::symbols::SymbolFlags::REFERENCED)
                }),
                None => section.name == b".gnu.warning",
            };
            if !used {
                continue;
            }
            let text = object.elf.section_data(&section.header).unwrap_or_default();
            let text = text.split(|&b| b == 0).next().unwrap_or_default();
            diagnostics.emit(
                Diagnostic::warning(String::from_utf8_lossy(text).into_owned())
                    .order(file.position.raw()),
            );
        }
    }
}

fn entry_address<F: crate::elf::read::ElfFormat>(
    addresses: &Addresses<'_, '_, F>,
    options: &LinkOptions,
    mode: Mode,
    diagnostics: &dyn DiagnosticSink,
) -> u64 {
    if mode.shared && options.entry.is_none() {
        return 0;
    }
    let name = options.entry.as_deref().unwrap_or("_start");
    if let Some(value) = parse_number(name) {
        return value;
    }
    let found = addresses
        .refs
        .symbols
        .lookup(&SymbolName::new(name.as_bytes()))
        .filter(|&id| {
            !matches!(
                addresses.refs.global_target(id, false).def,
                Def::Undefined { .. }
            )
        })
        .and_then(|id| addresses.globals.get(id.index()).copied());
    match found {
        Some(value) => value,
        None => {
            let text = addresses.layout.by_name(b".text").map_or(0, |s| s.addr);
            diagnostics.emit(Diagnostic::warning(format!(
                "cannot find entry symbol {name}; defaulting to {text:#x}"
            )));
            text
        }
    }
}