qld 0.1.1

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
//! Linker-script-driven layout (workstream W19, roadmap M3).
//!
//! Each test assembles inputs with the system `as`, links them with GNU ld
//! and with the `qld` binary under test using the same script and options,
//! and compares what `readelf` and `nm` report: section names, types,
//! flags, addresses, file offsets, sizes and alignments; program headers;
//! and symbol addresses. Raw outputs (`--oformat binary`, `ihex`, `srec`)
//! are compared byte for byte. Symbol *types* as `nm` prints them are not
//! compared: they follow the symbol table's section indexes, which the
//! symbol table writer chooses.
//!
//! A test prints `SKIPPED:` and passes when a tool it needs is missing.
//! Error tests check messages and that malformed scripts never panic.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::Arc;

use qld::args::{InputAttrs, InputKind, LinkOptions, OutputKind};
use qld::diag::Collect;

fn scratch(name: &str) -> PathBuf {
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR"))
        .join("script-link-tests")
        .join(name);
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

fn tool(name: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|dir| dir.join(name))
        .find(|candidate| candidate.is_file())
}

/// The GNU ld whose layout qld is compared against, when it is recent
/// enough. Layout details changed between binutils releases (2.42 orders
/// some orphan sections differently from 2.46, gives an empty `PT_LOAD` a
/// different file offset, and evaluates `NEXT` against another page size),
/// so comparisons only run against 2.44 or newer. qld's own assertions run
/// either way.
fn comparable_gnu_ld() -> Option<PathBuf> {
    let ld = gnu_ld()?;
    let out = Command::new(&ld).arg("--version").output().ok()?;
    let text = String::from_utf8_lossy(&out.stdout);
    let version = text.lines().next()?.split_whitespace().last()?;
    let mut parts = version.split('.');
    let major: u32 = parts.next()?.parse().ok()?;
    let minor: u32 = parts
        .next()?
        .trim_end_matches(|c: char| !c.is_ascii_digit())
        .parse()
        .ok()?;
    ((major, minor) >= (2, 44)).then_some(ld)
}

/// GNU ld, when installed: `ld.bfd`, or `ld` if it says it is GNU ld.
fn gnu_ld() -> Option<PathBuf> {
    if let Some(bfd) = tool("ld.bfd") {
        return Some(bfd);
    }
    let ld = tool("ld")?;
    let out = Command::new(&ld).arg("--version").output().ok()?;
    String::from_utf8_lossy(&out.stdout)
        .starts_with("GNU ld")
        .then_some(ld)
}

fn host_ok() -> bool {
    cfg!(all(target_os = "linux", target_arch = "x86_64"))
}

macro_rules! require_tools {
    () => {
        if !host_ok() {
            println!("SKIPPED: host is not x86-64 Linux");
            return;
        }
        for name in ["as", "readelf", "nm"] {
            if tool(name).is_none() {
                println!("SKIPPED: {name} not found");
                return;
            }
        }
    };
}

fn run(dir: &Path, program: &Path, args: &[&str]) -> Output {
    Command::new(program)
        .args(args)
        .current_dir(dir)
        .env("LC_ALL", "C")
        .output()
        .unwrap_or_else(|e| panic!("cannot run {}: {e}", program.display()))
}

fn stdout_ok(dir: &Path, program: &str, args: &[&str]) -> String {
    let output = run(dir, Path::new(program), args);
    assert!(
        output.status.success(),
        "`{program} {}` failed: {}",
        args.join(" "),
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn qld_path() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_qld"))
}

fn assemble(dir: &Path, name: &str, source: &str) {
    fs::write(dir.join(format!("{name}.s")), source).unwrap();
    stdout_ok(
        dir,
        "as",
        &["--64", "-o", &format!("{name}.o"), &format!("{name}.s")],
    );
}

/// What the comparison looks at.
#[derive(Debug, PartialEq)]
struct Summary {
    sections: Vec<String>,
    segments: Vec<String>,
    symbols: Vec<String>,
}

/// Sections whose contents are the linkers' own (version strings, symbol
/// tables) and differ by design.
const IGNORED_SECTIONS: &[&str] = &[".comment", ".symtab", ".strtab", ".shstrtab"];

fn summarize(dir: &Path, file: &str) -> Summary {
    let sections_text = stdout_ok(dir, "readelf", &["-SW", file]);
    let mut sections = Vec::new();
    for line in sections_text.lines() {
        let Some(rest) = line.trim_start().strip_prefix('[') else {
            continue;
        };
        let Some((_, rest)) = rest.split_once(']') else {
            continue;
        };
        let fields: Vec<&str> = rest.split_whitespace().collect();
        if fields
            .first()
            .is_none_or(|n| *n == "Nr" || IGNORED_SECTIONS.contains(n))
        {
            continue;
        }
        if fields.len() < 9 {
            continue;
        }
        // name type addr off size es [flags] lk inf al
        let align = fields.last().copied().unwrap_or_default();
        let flags = if fields.len() >= 10 { fields[6] } else { "" };
        sections.push(format!(
            "{} {} addr={} off={} size={} flags={flags} align={align}",
            fields[0], fields[1], fields[2], fields[3], fields[4]
        ));
    }
    let segments_text = stdout_ok(dir, "readelf", &["-lW", file]);
    let segments = segments_text
        .lines()
        .map(str::trim)
        .filter(|l| {
            [
                "LOAD", "NOTE", "TLS", "GNU_", "PHDR", "INTERP", "DYNAMIC", "NULL",
            ]
            .iter()
            .any(|p| l.starts_with(p))
        })
        .map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
        .collect();
    let nm = stdout_ok(dir, "nm", &["-n", file]);
    let symbols = nm
        .lines()
        .filter_map(|l| {
            let fields: Vec<&str> = l.split_whitespace().collect();
            (fields.len() == 3).then(|| format!("{} {}", fields[0], fields[2]))
        })
        .collect();
    Summary {
        sections,
        segments,
        symbols,
    }
}

/// Links `args` with GNU ld and qld into `gnu.out`/`qld.out` and asserts
/// the layouts are the same. Returns false (after printing `SKIPPED`) when
/// GNU ld is not installed.
fn compare(dir: &Path, args: &[&str]) -> bool {
    let Some(ld) = comparable_gnu_ld() else {
        println!("SKIPPED: no GNU ld 2.44 or newer to compare against");
        return false;
    };
    let mut gnu_args = args.to_vec();
    gnu_args.extend(["-o", "gnu.out"]);
    let gnu = run(dir, &ld, &gnu_args);
    assert!(
        gnu.status.success(),
        "GNU ld failed: {}",
        String::from_utf8_lossy(&gnu.stderr)
    );
    let mut qld_args = args.to_vec();
    qld_args.extend(["-o", "qld.out"]);
    let qld = run(dir, &qld_path(), &qld_args);
    assert!(
        qld.status.success(),
        "qld {} failed: {}",
        qld_args.join(" "),
        String::from_utf8_lossy(&qld.stderr)
    );
    let expected = summarize(dir, "gnu.out");
    let actual = summarize(dir, "qld.out");
    assert_eq!(
        expected.sections,
        actual.sections,
        "sections differ in {}",
        dir.display()
    );
    assert_eq!(
        expected.segments,
        actual.segments,
        "segments differ in {}",
        dir.display()
    );
    assert_eq!(
        expected.symbols,
        actual.symbols,
        "symbols differ in {}",
        dir.display()
    );
    true
}

/// Links with both linkers in each raw format and compares the bytes.
fn compare_raw(dir: &Path, args: &[&str]) {
    let Some(ld) = gnu_ld() else {
        println!("SKIPPED: GNU ld not found");
        return;
    };
    for format in ["binary", "ihex", "srec"] {
        // Same output name for both: srec records it.
        let name = format!("image.{format}");
        let mut full = args.to_vec();
        full.extend(["--oformat", format, "-o", &name]);
        let gnu = run(dir, &ld, &full);
        assert!(gnu.status.success(), "GNU ld --oformat {format} failed");
        let expected = fs::read(dir.join(&name)).unwrap();
        let qld = run(dir, &qld_path(), &full);
        assert!(
            qld.status.success(),
            "qld --oformat {format} failed: {}",
            String::from_utf8_lossy(&qld.stderr)
        );
        let actual = fs::read(dir.join(&name)).unwrap();
        assert!(
            expected == actual,
            "{format} output differs ({} vs {} bytes) in {}",
            expected.len(),
            actual.len(),
            dir.display()
        );
    }
}

/// Runs qld alone; returns (success, stderr).
fn qld_only(dir: &Path, args: &[&str]) -> (bool, String) {
    let out = run(dir, &qld_path(), args);
    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(!stderr.contains("panicked"), "qld panicked: {stderr}");
    (out.status.success(), stderr)
}

// ---------------------------------------------------------------------------
// Inputs.
// ---------------------------------------------------------------------------

const START: &str = r#"
.section .vectors,"a"
.globl vectors
vectors:
.quad reset_handler
.quad nmi_handler
.quad 0

.text
.globl reset_handler
reset_handler:
  mov $_sidata, %rsi
  mov $_sdata, %rdi
  mov $_edata, %rcx
  sub %rdi, %rcx
  rep movsb
  mov $_sbss, %rdi
  mov $_ebss, %rcx
  sub %rdi, %rcx
  xor %eax, %eax
  rep stosb
  call main
  hlt

.section .text.nmi,"ax"
.p2align 4
.globl nmi_handler
nmi_handler:
  iretq

.section .rodata
.globl message
message:
.asciz "hello, bare metal"

.data
.globl counter
.p2align 3
counter:
.quad 42

.bss
.globl buffer
buffer:
.zero 100
"#;

const MAIN: &str = r#"
.section .text.main,"ax"
.globl main
main:
  mov counter(%rip), %rax
  lea message(%rip), %rdx
  ret

.section .data.table,"aw"
.p2align 4
table:
.quad main, counter

.section .init_array.100,"aw"
.quad main
.section .init_array.5,"aw"
.quad main

.section .bss.big,"aw",@nobits
.p2align 6
big:
.zero 256
"#;

/// A Cortex-M style layout on x86-64: a vector table at the start of flash,
/// code and read-only data in flash, `.data` running in RAM but loaded from
/// flash, and `.bss` in RAM.
const FLASH_SCRIPT: &str = r#"
ENTRY(reset_handler)
MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 64K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 16K
}
_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
  .isr_vector :
  {
    . = ALIGN(8);
    KEEP(*(.vectors))
    . = ALIGN(8);
  } >FLASH
  .text :
  {
    *(.text)
    *(.text*)
    . = ALIGN(8);
    _etext = .;
  } >FLASH =0x90909090
  .rodata : { *(.rodata) *(.rodata*) BYTE(0x11) SHORT(0x2233) LONG(0x44556677) QUAD(0x8899aabbccddeeff) . = ALIGN(8); } >FLASH
  .init_array :
  {
    PROVIDE_HIDDEN (__init_array_start = .);
    KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*)))
    PROVIDE_HIDDEN (__init_array_end = .);
  } >FLASH
  _sidata = LOADADDR(.data);
  .data :
  {
    . = ALIGN(8);
    _sdata = .;
    *(.data)
    *(.data*)
    . = ALIGN(8);
    _edata = .;
  } >RAM AT> FLASH
  .bss (NOLOAD) :
  {
    _sbss = .;
    *(.bss)
    *(.bss*)
    *(COMMON)
    . = ALIGN(8);
    _ebss = .;
  } >RAM
  ASSERT(SIZEOF(.data) + SIZEOF(.bss) <= LENGTH(RAM), "RAM overflow")
  /DISCARD/ : { *(.note.gnu.property) }
}
"#;

fn bare_metal(dir: &Path) {
    assemble(dir, "start", START);
    assemble(dir, "main", MAIN);
}

// ---------------------------------------------------------------------------
// Layout tests against GNU ld.
// ---------------------------------------------------------------------------

#[test]
fn memory_regions_load_addresses_and_data_commands() {
    require_tools!();
    let dir = scratch("flash");
    bare_metal(&dir);
    fs::write(dir.join("flash.ld"), FLASH_SCRIPT).unwrap();
    if compare(&dir, &["-T", "flash.ld", "start.o", "main.o"]) {
        compare_raw(&dir, &["-T", "flash.ld", "start.o", "main.o"]);
    }
}

#[test]
fn program_headers_from_phdrs() {
    require_tools!();
    let dir = scratch("phdrs");
    bare_metal(&dir);
    fs::write(
        dir.join("phdrs.ld"),
        r#"
ENTRY(reset_handler)
PHDRS
{
  headers PT_PHDR PHDRS;
  text PT_LOAD FILEHDR PHDRS FLAGS(5);
  data PT_LOAD AT(0x800000) FLAGS(6);
  note PT_NOTE;
}
SECTIONS
{
  . = 0x400000 + SIZEOF_HEADERS;
  .text : { *(.vectors) *(.text*) } :text
  .rodata : { *(.rodata*) } :text
  .note.gnu.property : { *(.note.gnu.property) } :text :note
  . = ALIGN(0x1000);
  .data : { *(.data*) *(.init_array*) } :data
  .bss : { *(.bss*) } :data
  _sidata = LOADADDR(.data); _sdata = ADDR(.data); _edata = _sdata + SIZEOF(.data);
  _sbss = ADDR(.bss); _ebss = _sbss + SIZEOF(.bss);
}
"#,
    )
    .unwrap();
    compare(&dir, &["-T", "phdrs.ld", "start.o", "main.o"]);
}

#[test]
fn orphans_follow_sections_with_similar_flags() {
    require_tools!();
    let dir = scratch("orphans");
    bare_metal(&dir);
    assemble(
        &dir,
        "extra",
        r#"
.section .fast_code,"ax"
.globl fast
fast: ret
.section .config,"a"
.quad 1
.section .state,"aw"
.quad 2
.section .scratch,"aw",@nobits
.zero 32
.section .info_only,""
.asciz "not allocated"
.section .note.custom,"a",@note
.long 4, 4, 1
.asciz "abc"
"#,
    );
    fs::write(
        dir.join("orphans.ld"),
        r#"
ENTRY(reset_handler)
SECTIONS
{
  . = 0x100000;
  .text : { *(.text*) }
  _etext = .;
  . = ALIGN(0x1000);
  .rodata : { *(.rodata*) *(.vectors) }
  .data : { *(.data*) *(.init_array*) }
  .bss : { *(.bss*) }
  _sidata = .; _sdata = .; _edata = .; _sbss = ADDR(.bss); _ebss = .;
}
"#,
    )
    .unwrap();
    compare(&dir, &["-T", "orphans.ld", "start.o", "main.o", "extra.o"]);
    // Without SECTIONS every section is an orphan.
    fs::write(
        dir.join("none.ld"),
        "_sidata = 0; _sdata = 0; _edata = 0; _sbss = 0; _ebss = 0;\n",
    )
    .unwrap();
    compare(&dir, &["-T", "none.ld", "start.o", "main.o", "extra.o"]);
}

#[test]
fn overlays_and_expressions() {
    require_tools!();
    let dir = scratch("overlay");
    bare_metal(&dir);
    assemble(
        &dir,
        "ovl",
        r#"
.section .ov1,"ax"
.globl in_ov1
in_ov1: .fill 20, 1, 0xc3
.section .ov2,"ax"
.globl in_ov2
in_ov2: .fill 40, 1, 0xc3
"#,
    );
    fs::write(
        dir.join("ovl.ld"),
        r#"
ENTRY(reset_handler)
SECTIONS
{
  . = 0x10000;
  .text ALIGN(0x100) : SUBALIGN(32) { *(.vectors) *(.text*) }
  text_end = .;
  OVERLAY 0x20000 : AT (0x30000)
  {
    .ov1 { *(.ov1) }
    .ov2 { *(.ov2) }
  }
  after_overlay = .;
  .rodata MAX(., 0x28000) : { *(.rodata*) }
  sizes = SIZEOF(.ov1) + SIZEOF(.ov2) + ALIGNOF(.text);
  next_align = ALIGNOF(NEXT_SECTION);
  .data : ALIGN(0x40) { *(.data*) *(.init_array*) LONG(DEFINED(text_end) ? 1 : 2) LONG(DEFINED(nosuch) ? 3 : 4) }
  .bss : { *(.bss*) }
  _sidata = ABSOLUTE(LOADADDR(.data)); _sdata = ADDR(.data); _edata = . ;
  _sbss = ADDR(.bss); _ebss = _sbss + SIZEOF(.bss);
  page = CONSTANT(MAXPAGESIZE);
  log = LOG2CEIL(sizes);
}
"#,
    )
    .unwrap();
    if compare(&dir, &["-T", "ovl.ld", "start.o", "main.o", "ovl.o"]) {
        compare_raw(&dir, &["-T", "ovl.ld", "start.o", "main.o", "ovl.o"]);
    }
}

#[test]
fn input_section_selection_and_sorting() {
    require_tools!();
    let dir = scratch("select");
    bare_metal(&dir);
    assemble(
        &dir,
        "sorted",
        r#"
.section .table.zeta,"a"
.byte 1
.section .table.alpha,"a"
.p2align 3
.quad 2
.section .table.mid,"a"
.p2align 1
.short 3
.section .ctors.65000,"aw"
.quad 4
.section .ctors.10,"aw"
.quad 5
"#,
    );
    stdout_ok(&dir, "ar", &["rcs", "libsorted.a", "sorted.o"]);
    fs::write(
        dir.join("select.ld"),
        r#"
ENTRY(reset_handler)
SECTIONS
{
  . = 0x200000;
  .text : { *(EXCLUDE_FILE(*main.o) .text*) main.o(.text*) *(.vectors) }
  .by_name : { KEEP(*(SORT_BY_NAME(.table.*))) }
  .by_align : { libsorted.a:sorted.o(SORT_BY_ALIGNMENT(.table.*)) }
  .ctors : { KEEP(*(SORT_BY_INIT_PRIORITY(.ctors.*))) }
  .rodata : { INPUT_SECTION_FLAGS (!SHF_WRITE) *(.rodata*) }
  .data : { *(.data*) *(.init_array*) }
  .bss : { *(.bss*) *(COMMON) }
  _sidata = 0; _sdata = ADDR(.data); _edata = .; _sbss = ADDR(.bss); _ebss = .;
  /DISCARD/ : { *(.note.*) }
}
"#,
    )
    .unwrap();
    compare(
        &dir,
        &[
            "-T",
            "select.ld",
            "start.o",
            "main.o",
            "--whole-archive",
            "libsorted.a",
        ],
    );
}

#[test]
fn region_aliases_and_attribute_placement() {
    require_tools!();
    let dir = scratch("regions");
    bare_metal(&dir);
    fs::write(
        dir.join("regions.ld"),
        r#"
ENTRY(reset_handler)
MEMORY
{
  rom (rx) : ORIGIN = 0x1000, LENGTH = 0x4000
  ram (rw!x) : ORIGIN = 0x80000, LENGTH = 0x8000
}
REGION_ALIAS("REGION_TEXT", rom);
SECTIONS
{
  .text : { *(.vectors) *(.text*) } > REGION_TEXT
  .rodata : { *(.rodata*) }
  .data : { *(.data*) *(.init_array*) }
  .bss : { *(.bss*) }
  _sidata = LOADADDR(.data); _sdata = ADDR(.data); _edata = _sdata + SIZEOF(.data);
  _sbss = ADDR(.bss); _ebss = _sbss + SIZEOF(.bss);
  /DISCARD/ : { *(.note.*) }
}
"#,
    )
    .unwrap();
    compare(&dir, &["-T", "regions.ld", "start.o", "main.o"]);
}

#[test]
fn insert_into_the_default_layout() {
    require_tools!();
    let dir = scratch("insert");
    assemble(
        &dir,
        "prog",
        r#"
.globl _start
.text
_start:
  mov $60, %eax
  xor %edi, %edi
  syscall
.section .mydata,"aw"
.globl mydata_item
mydata_item: .quad 7
.data
.quad 1
"#,
    );
    fs::write(
        dir.join("insert.ld"),
        r#"
SECTIONS
{
  .mydata : { __mydata_start = .; KEEP(*(.mydata)) __mydata_end = .; }
}
INSERT AFTER .data;
"#,
    )
    .unwrap();
    compare(&dir, &["-static", "-T", "insert.ld", "prog.o"]);
}

#[test]
fn command_line_section_addresses() {
    require_tools!();
    let dir = scratch("ttext");
    assemble(
        &dir,
        "prog",
        r#"
.globl _start
.text
_start:
  mov $60, %eax
  xor %edi, %edi
  syscall
.data
.globl value
value: .quad 1
.bss
.zero 16
"#,
    );
    compare(
        &dir,
        &["-static", "-Ttext=0x500000", "-Tdata=0x600000", "prog.o"],
    );
    compare(
        &dir,
        &["-static", "--section-start=.bss=0x700000", "prog.o"],
    );
    compare(&dir, &["-static", "-N", "prog.o"]);
    compare(&dir, &["-static", "-n", "prog.o"]);
    compare(
        &dir,
        &["-static", "-Ttext-segment=0x800000", "-N", "prog.o"],
    );
}

#[test]
fn binary_inputs_define_start_end_and_size() {
    require_tools!();
    let dir = scratch("binary-input");
    bare_metal(&dir);
    fs::write(dir.join("blob-1.bin"), b"payload bytes\0\x01\x02").unwrap();
    fs::write(dir.join("flash.ld"), FLASH_SCRIPT).unwrap();
    let args = [
        "-T",
        "flash.ld",
        "start.o",
        "main.o",
        "-b",
        "binary",
        "blob-1.bin",
        "-b",
        "default",
    ];
    if compare(&dir, &args) {
        let nm = stdout_ok(&dir, "nm", &["qld.out"]);
        assert!(nm.contains("_binary_blob_1_bin_start"), "{nm}");
        assert!(nm.contains("A _binary_blob_1_bin_size"), "{nm}");
        compare_raw(&dir, &args);
    }
}

// ---------------------------------------------------------------------------
// Errors.
// ---------------------------------------------------------------------------

#[test]
fn region_overflow_is_reported_like_gnu() {
    require_tools!();
    let dir = scratch("overflow");
    bare_metal(&dir);
    fs::write(
        dir.join("small.ld"),
        FLASH_SCRIPT.replace("LENGTH = 64K", "LENGTH = 16"),
    )
    .unwrap();
    let (ok, stderr) = qld_only(&dir, &["-T", "small.ld", "start.o", "main.o", "-o", "out"]);
    assert!(!ok);
    assert!(
        stderr.contains("will not fit in region `FLASH'"),
        "{stderr}"
    );
    assert!(stderr.contains("region `FLASH' overflowed by"), "{stderr}");
    if let Some(ld) = gnu_ld() {
        let gnu = run(
            &dir,
            &ld,
            &["-T", "small.ld", "start.o", "main.o", "-o", "gnu"],
        );
        let gnu_err = String::from_utf8_lossy(&gnu.stderr);
        let wanted = gnu_err
            .lines()
            .find(|l| l.contains("overflowed by"))
            .and_then(|l| l.split_once("region"))
            .map(|(_, rest)| rest.to_string())
            .unwrap_or_default();
        assert!(stderr.contains(&wanted), "GNU: {gnu_err}\nqld: {stderr}");
    }
}

#[test]
fn failed_assertions_fail_the_link() {
    require_tools!();
    let dir = scratch("assert");
    bare_metal(&dir);
    fs::write(
        dir.join("assert.ld"),
        FLASH_SCRIPT.replace(
            "<= LENGTH(RAM), \"RAM overflow\"",
            "<= 8, \"RAM too small for this image\"",
        ),
    )
    .unwrap();
    let (ok, stderr) = qld_only(&dir, &["-T", "assert.ld", "start.o", "main.o", "-o", "out"]);
    assert!(!ok);
    assert!(stderr.contains("RAM too small for this image"), "{stderr}");
}

#[test]
fn diverging_scripts_are_errors() {
    require_tools!();
    let dir = scratch("diverge");
    bare_metal(&dir);
    // Each pass moves `.text` past where the previous pass put `.data`.
    fs::write(
        dir.join("diverge.ld"),
        r#"
SECTIONS
{
  .text : { *(.text*) *(.vectors) }
  .gap ADDR(.data) + SIZEOF(.data) + 0x1000 : { LONG(0) }
  .data : { *(.data*) *(.init_array*) }
  _sidata = 0; _sdata = 0; _edata = 0; _sbss = 0; _ebss = 0;
}
"#,
    )
    .unwrap();
    let (ok, stderr) = qld_only(
        &dir,
        &["-T", "diverge.ld", "start.o", "main.o", "-o", "out"],
    );
    assert!(!ok, "{stderr}");
    assert!(stderr.contains("did not converge"), "{stderr}");
}

#[test]
fn undefined_symbols_in_expressions_are_errors() {
    require_tools!();
    let dir = scratch("undefined-expr");
    bare_metal(&dir);
    fs::write(
        dir.join("undef.ld"),
        FLASH_SCRIPT.replace(
            "_estack = ORIGIN(RAM) + LENGTH(RAM);",
            "_estack = no_such_symbol + 1;",
        ),
    )
    .unwrap();
    let (ok, stderr) = qld_only(&dir, &["-T", "undef.ld", "start.o", "main.o", "-o", "out"]);
    assert!(!ok);
    assert!(
        stderr.contains("undefined symbol `no_such_symbol' referenced in expression"),
        "{stderr}"
    );
}

#[test]
fn orphan_handling_error_names_the_section() {
    require_tools!();
    let dir = scratch("orphan-error");
    bare_metal(&dir);
    fs::write(
        dir.join("strict.ld"),
        FLASH_SCRIPT.replace("*(.text*)", "*(.text)"),
    )
    .unwrap();
    let (ok, stderr) = qld_only(
        &dir,
        &[
            "--orphan-handling=error",
            "-T",
            "strict.ld",
            "start.o",
            "main.o",
            "-o",
            "out",
        ],
    );
    assert!(!ok);
    assert!(
        stderr.contains("unplaced orphan section `.text.nmi' from `start.o'"),
        "{stderr}"
    );
}

#[test]
fn nocrossrefs_prohibits_references_between_sections() {
    require_tools!();
    let dir = scratch("nocrossrefs");
    assemble(&dir, "start", START);
    assemble(&dir, "main", MAIN);
    // `main` (in .text) reads `counter` (in .data), and .data holds a
    // pointer to `main`.
    let script = FLASH_SCRIPT.replace(
        "ENTRY(reset_handler)",
        "ENTRY(reset_handler)\nNOCROSSREFS(.text .data)\n",
    );
    fs::write(dir.join("ncr.ld"), &script).unwrap();
    let args = ["-T", "ncr.ld", "start.o", "main.o", "-o", "out"];
    let (ok, stderr) = qld_only(&dir, &args);
    assert!(!ok, "{stderr}");
    assert!(
        stderr.contains("prohibited cross reference from .text to `counter' in .data"),
        "{stderr}"
    );
    assert!(
        stderr.contains("prohibited cross reference from .data to `main' in .text"),
        "{stderr}"
    );
    if let Some(ld) = gnu_ld() {
        let gnu = run(
            &dir,
            &ld,
            &["-T", "ncr.ld", "start.o", "main.o", "-o", "gnu"],
        );
        let gnu_err = String::from_utf8_lossy(&gnu.stderr);
        assert!(!gnu.status.success(), "{gnu_err}");
        for line in gnu_err.lines().filter(|l| l.contains("prohibited")) {
            let (_, message) = line.split_once("prohibited").unwrap_or(("", line));
            assert!(
                stderr.contains(message.trim()),
                "GNU: {line}\nqld: {stderr}"
            );
        }
    }

    // NOCROSSREFS_TO only checks references to the first section, so
    // .data -> .text stays legal while .text -> .data does not.
    let script = script.replace("NOCROSSREFS(.text .data)", "NOCROSSREFS_TO(.data .text)");
    fs::write(dir.join("ncr.ld"), &script).unwrap();
    let (ok, stderr) = qld_only(&dir, &args);
    assert!(!ok, "{stderr}");
    assert!(
        stderr.contains("prohibited cross reference from .text to `counter' in .data"),
        "{stderr}"
    );
    assert!(
        !stderr.contains("from .data to `main'"),
        "references to the first section only: {stderr}"
    );
}

/// Truncated and corrupted scripts must give errors, never panics.
#[test]
fn corrupted_scripts_never_panic() {
    require_tools!();
    let dir = scratch("corrupt-script");
    bare_metal(&dir);
    let objects: Vec<(String, Arc<[u8]>)> = ["start.o", "main.o"]
        .iter()
        .map(|n| (n.to_string(), Arc::from(fs::read(dir.join(n)).unwrap())))
        .collect();
    let original = FLASH_SCRIPT.as_bytes();
    let mut state = 0x2545_f491_4f6c_dd1du64;
    let mut next = move || {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        state
    };
    let pool = rayon::ThreadPoolBuilder::new()
        .num_threads(2)
        .build()
        .unwrap();
    let script = dir.join("broken.ld");
    for round in 0..400 {
        let mut data = original.to_vec();
        match round % 3 {
            0 => data.truncate((next() as usize) % original.len()),
            1 => {
                for _ in 0..3 {
                    let at = (next() as usize) % data.len();
                    data[at] = b"(){};=.*+-<>ABCDEFGHILMNOPRSTXYZ0123456789,:!/\"x"
                        [(next() as usize) % 47];
                }
            }
            _ => {
                let at = (next() as usize) % data.len();
                data.insert(at, b"0123456789+-*/()"[(next() as usize) % 16]);
            }
        }
        fs::write(&script, &data).unwrap();
        let mut options = LinkOptions::new();
        options.kind = OutputKind::StaticExecutable;
        options.output = Some(dir.join("out"));
        options.push_input(InputKind::Script(script.clone()), InputAttrs::default());
        for (name, bytes) in &objects {
            options.push_input(
                InputKind::Bytes {
                    name: name.clone(),
                    data: Arc::clone(bytes),
                },
                InputAttrs::default(),
            );
        }
        let sink = Collect::new();
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            pool.install(|| qld::elf::link(&options, &sink))
        }));
        assert!(
            result.is_ok(),
            "panic on script corruption round {round}:\n{}",
            String::from_utf8_lossy(&data)
        );
    }
}

// ---------------------------------------------------------------------------
// Relocatable output with a script (`-r -T`), as the kernel links modules.
// ---------------------------------------------------------------------------

/// One section of a relocatable file: name, type, flags, size, alignment,
/// entry size and contents.
type RelSection = (String, u32, u64, u64, u64, u64, Vec<u8>);

/// The sections of a relocatable ELF file in header order. Contents are
/// left empty for `SHT_NOBITS`, groups, relocations (compared through
/// readelf) and the linkers' own symbol and string tables.
fn relocatable_sections(path: &Path) -> Vec<RelSection> {
    let data = fs::read(path).unwrap();
    let word = |at: usize, n: usize| -> u64 {
        let mut bytes = [0u8; 8];
        bytes[..n].copy_from_slice(&data[at..at + n]);
        u64::from_le_bytes(bytes)
    };
    let shoff = word(0x28, 8) as usize;
    let shnum = word(0x3c, 2) as usize;
    let shstrndx = word(0x3e, 2) as usize;
    let header = |i: usize| shoff + i * 64;
    let names = word(header(shstrndx) + 24, 8) as usize;
    let mut out = Vec::new();
    for i in 1..shnum {
        let h = header(i);
        let name_at = names + word(h, 4) as usize;
        let end = data[name_at..].iter().position(|&b| b == 0).unwrap();
        let name = String::from_utf8_lossy(&data[name_at..name_at + end]).into_owned();
        let sh_type = word(h + 4, 4) as u32;
        let (offset, size) = (word(h + 24, 8) as usize, word(h + 32, 8));
        let contents = if matches!(sh_type, 2 | 3 | 4 | 8 | 17) {
            Vec::new()
        } else if name == ".note.gnu.build-id" {
            // The note header; the hash is of different outputs.
            data[offset..offset + 16].to_vec()
        } else {
            data[offset..offset + size as usize].to_vec()
        };
        let size = if matches!(sh_type, 2 | 3) { 0 } else { size };
        out.push((
            name,
            sh_type,
            word(h + 8, 8),
            size,
            word(h + 48, 8),
            word(h + 56, 8),
            contents,
        ));
    }
    out
}

/// Symbols as `name value section binding type visibility`, sorted, without
/// section symbols and file symbols.
fn relocatable_symbols(dir: &Path, file: &str) -> Vec<String> {
    let text = stdout_ok(dir, "readelf", &["-sW", file]);
    let sections = stdout_ok(dir, "readelf", &["-SW", file]);
    let section_name = |index: &str| -> String {
        let Ok(index) = index.parse::<usize>() else {
            return index.to_string();
        };
        sections
            .lines()
            .find_map(|l| {
                let rest = l.trim_start().strip_prefix('[')?;
                let (number, rest) = rest.split_once(']')?;
                (number.trim().parse::<usize>().ok()? == index)
                    .then(|| rest.split_whitespace().next().unwrap_or("").to_string())
            })
            .unwrap_or_default()
    };
    let mut symbols: Vec<String> = text
        .lines()
        .filter_map(|l| {
            let f: Vec<&str> = l.split_whitespace().collect();
            if f.len() < 8 || !f[0].ends_with(':') || f[3] == "SECTION" || f[3] == "FILE" {
                return None;
            }
            Some(format!(
                "{} {} {} {} {} {}",
                f[7],
                f[1],
                section_name(f[6]),
                f[4],
                f[3],
                f[5]
            ))
        })
        .collect();
    symbols.sort();
    symbols
}

/// Relocations as `section: offset type symbol+addend`.
fn relocatable_relocations(dir: &Path, file: &str) -> Vec<String> {
    let text = stdout_ok(dir, "readelf", &["-rW", file]);
    let mut section = String::new();
    let mut out = Vec::new();
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("Relocation section '") {
            section = rest.split('\'').next().unwrap_or("").to_string();
            continue;
        }
        let f: Vec<&str> = line.split_whitespace().collect();
        if f.len() >= 3 && f[0].chars().all(|c| c.is_ascii_hexdigit()) {
            let target = f.get(4..).map(|r| r.join(" ")).unwrap_or_default();
            out.push(format!("{section}: {} {} {target}", f[0], f[2]));
        }
    }
    out
}

/// Links `-r` with both linkers and compares sections (in order, with
/// contents), symbols and relocations. Addresses are not compared:
/// relocatable outputs have none.
fn compare_relocatable(dir: &Path, args: &[&str]) {
    let Some(ld) = comparable_gnu_ld() else {
        println!("SKIPPED: no GNU ld 2.44 or newer to compare against");
        return;
    };
    for (linker, out) in [(ld, "gnu.o"), (qld_path(), "qld.o")] {
        let mut full = vec!["-r"];
        full.extend_from_slice(args);
        full.extend(["-o", out]);
        let result = run(dir, &linker, &full);
        assert!(
            result.status.success(),
            "{} {} failed: {}",
            linker.display(),
            full.join(" "),
            String::from_utf8_lossy(&result.stderr)
        );
    }
    let expected = relocatable_sections(&dir.join("gnu.o"));
    let actual = relocatable_sections(&dir.join("qld.o"));
    let names = |s: &[RelSection]| s.iter().map(|x| x.0.clone()).collect::<Vec<_>>();
    assert_eq!(
        names(&expected),
        names(&actual),
        "section order differs in {}",
        dir.display()
    );
    for (e, a) in expected.iter().zip(&actual) {
        assert_eq!(e, a, "section {} differs in {}", e.0, dir.display());
    }
    assert_eq!(
        relocatable_symbols(dir, "gnu.o"),
        relocatable_symbols(dir, "qld.o"),
        "symbols differ in {}",
        dir.display()
    );
    assert_eq!(
        relocatable_relocations(dir, "gnu.o"),
        relocatable_relocations(dir, "qld.o"),
        "relocations differ in {}",
        dir.display()
    );
}

/// A module-style link: sorted tables, `/DISCARD/`, sections with explicit
/// addresses and `ALIGN`, data commands, `. = ALIGN(8)` (which pads by the
/// addresses GNU ld gives sections while running the script), symbols
/// inside and outside output sections, `PROVIDE`, orphans (same-named ones
/// join the script's section), a COMDAT group (never matched by wildcards
/// in `-r`) and a link-order section.
#[test]
fn relocatable_link_with_a_script() {
    require_tools!();
    let dir = scratch("relocatable-script");
    assemble(
        &dir,
        "a",
        r#"
	.section .rodata,"a"
ra:	.byte 1
	.section .data.bar,"aw"
	.globl bar
bar:	.long 3
	.section .text.a,"ax"
	.globl fa
fa:	ret
	.section .init.text,"ax"
	.globl init_a
init_a:	nop
	ret
	.section .empty,"aw"
	.section alloc_tags,"aw"
	.quad 7
	.section .tbl,"a"
	.globl tbl_a
tbl_a:	.quad ra
	.section "__ksymtab+foo","a"
	.quad fa
	.section "__ksymtab+bar","a"
	.quad bar
	.section .discard.x,"a"
	.quad 1
	.section .text.inl,"axG",@progbits,inl,comdat
	.weak inl
inl:	ret
	.section __patchable_function_entries,"awo",@progbits,.text.a
	.quad fa
"#,
    );
    assemble(
        &dir,
        "b",
        r#"
	.section .rodata,"a"
rb:	.byte 2
	.section .text.b,"ax"
	.globl fb
fb:	nop
	ret
	.section alloc_tags,"aw"
	.quad 8
	.section .tbl,"a"
	.quad rb
	.section .text.inl,"axG",@progbits,inl,comdat
	.weak inl
inl:	ret
	.section .bss,"aw",@nobits
	.zero 16
"#,
    );
    fs::write(
        dir.join("module.ld"),
        r#"
abs_sym = 0x1234;
SECTIONS {
 /DISCARD/ : { *(.discard) *(.discard.*) }
 __ksymtab 0 : ALIGN(8) { *(SORT(__ksymtab+*)) }
 .text : { *(.text.b) *(.text .text.*) }
 .rodata : { a.o(.rodata) }
 .onlysyms : { only_start = .; only_end = .; }
 .dataish : { BYTE(1) SHORT(2) }
 .codetag.alloc_tags : { . = ALIGN(8); __start_alloc_tags = .; KEEP(*(alloc_tags)) __stop_alloc_tags = .; }
 .tbl : { tbl_start = .; *(.tbl) tbl_end = .; PROVIDE(tbl_unused = .); tbl_size = tbl_end - tbl_start; }
 .emptyout : { *(.nothing) }
 .aligned : { . = ALIGN(16); *(.data.bar) . = . + 4; after = .; }
}
alias_fa = fa;
alias_off = fa + 1;
"#,
    )
    .unwrap();
    compare_relocatable(&dir, &["-T", "module.ld", "a.o", "b.o"]);
    // Without a script, x86-64 relocatable output follows GNU ld's built-in
    // `-r` layout, with `--build-id` first.
    compare_relocatable(&dir, &["--build-id", "a.o", "b.o"]);
}

/// `-T` scripts and the scripts they `INCLUDE` are read through
/// `LinkOptions::input_provider`, like other inputs, and give the same
/// output as the files on disk.
#[test]
fn scripts_from_the_input_provider() {
    require_tools!();
    let dir = scratch("provider-script");
    bare_metal(&dir);
    fs::write(dir.join("flash.ld"), FLASH_SCRIPT).unwrap();
    let (ok, stderr) = qld_only(
        &dir,
        &["-T", "flash.ld", "start.o", "main.o", "-o", "disk.out"],
    );
    assert!(ok, "{stderr}");
    let memory = qld::input::source::MemoryFiles::new()
        .with("virtual/outer.ld", &b"INCLUDE inner.ld\n"[..])
        .with("virtual/inner.ld", FLASH_SCRIPT.as_bytes().to_vec());
    let mut options = LinkOptions::new();
    options.kind = OutputKind::StaticExecutable;
    options.output = Some(dir.join("memory.out"));
    options.search_paths.push("virtual".into());
    options.input_provider = Some(Arc::new(memory));
    options.push_input(
        InputKind::Script("virtual/outer.ld".into()),
        InputAttrs::default(),
    );
    for name in ["start.o", "main.o"] {
        options.push_input(InputKind::File(dir.join(name)), InputAttrs::default());
    }
    let sink = Collect::new();
    qld::elf::link(&options, &sink).unwrap_or_else(|e| panic!("{e}: {:?}", sink));
    assert_eq!(
        fs::read(dir.join("disk.out")).unwrap(),
        fs::read(dir.join("memory.out")).unwrap(),
        "the scripts from memory give another output"
    );
}

// ---------------------------------------------------------------------------
// `--defsym` with linker script expressions.
// ---------------------------------------------------------------------------

const DEFSYM_INPUT: &str = r#"
	.text
	.globl _start
_start:
	mov $60, %eax
	syscall
	.globl fn
	.type fn,@function
fn:	ret
	.size fn, 1
	.data
	.globl table, table_end
table:	.quad 1,2,3
table_end:
	.quad use_me
"#;

/// `--defsym` options exercising GNU ld's expression rules: arithmetic
/// makes a value absolute, a lone symbol keeps its section, the type of the
/// one symbol an expression reads is copied, built-ins read the final
/// layout, and forward references to later `--defsym`s settle.
const DEFSYMS: &[&str] = &[
    "--defsym=d_off=fn+4",
    "--defsym=d_mul=fn*2",
    "--defsym=d_addr=ADDR(.data)+0x10",
    "--defsym=d_size=SIZEOF(.text)",
    "--defsym=d_diff=table_end-table",
    "--defsym=d_later=table+8",
    "--defsym=d_cond=DEFINED(fn)?fn:0",
    "--defsym=d_align=ALIGN(table,0x100)",
    "--defsym=d_abs=ABSOLUTE(fn)",
    "--defsym=d_page=CONSTANT(MAXPAGESIZE)",
    "--defsym=d_load=LOADADDR(.data)",
    "--defsym=d_max=MAX(fn,table)",
    "--defsym=d_alias=fn",
    "--defsym=use_me=table_end-8",
];

/// `name value type binding absolute` of the symbols starting with `d_`
/// or named `use_me`, sorted.
fn defsym_symbols(dir: &Path, file: &str) -> Vec<String> {
    let text = stdout_ok(dir, "readelf", &["-sW", file]);
    let mut out: Vec<String> = text
        .lines()
        .filter_map(|l| {
            let f: Vec<&str> = l.split_whitespace().collect();
            let name = *f.get(7)?;
            (name.starts_with("d_") || name == "use_me" || name == "script_uses").then(|| {
                format!(
                    "{name} {} {} {} {}",
                    f[1],
                    f[3],
                    f[4],
                    if f[6] == "ABS" { "ABS" } else { "section" }
                )
            })
        })
        .collect();
    out.sort();
    out.dedup();
    out
}

fn compare_defsyms(dir: &Path, args: &[&str]) {
    let Some(ld) = comparable_gnu_ld() else {
        println!("SKIPPED: no GNU ld 2.44 or newer to compare against");
        return;
    };
    for (linker, out) in [(ld, "gnu.out"), (qld_path(), "qld.out")] {
        let mut full = args.to_vec();
        full.extend(["-o", out]);
        let result = run(dir, &linker, &full);
        assert!(
            result.status.success(),
            "{} {} failed: {}",
            linker.display(),
            full.join(" "),
            String::from_utf8_lossy(&result.stderr)
        );
    }
    let expected = defsym_symbols(dir, "gnu.out");
    assert!(expected.len() >= 10, "{expected:?}");
    assert_eq!(
        expected,
        defsym_symbols(dir, "qld.out"),
        "--defsym symbols differ in {}",
        dir.display()
    );
}

#[test]
fn defsym_expressions_like_gnu_ld() {
    require_tools!();
    let dir = scratch("defsym-expressions");
    assemble(&dir, "a", DEFSYM_INPUT);
    let mut args = vec!["-static", "a.o"];
    args.extend_from_slice(DEFSYMS);
    compare_defsyms(&dir, &args);
}

/// Under a linker script, `--defsym`s are assignments before the script's
/// own statements, which may read them.
#[test]
fn defsym_expressions_with_a_script() {
    require_tools!();
    let dir = scratch("defsym-script");
    assemble(&dir, "a", DEFSYM_INPUT);
    fs::write(
        dir.join("t.ld"),
        "SECTIONS {
  . = 0x10000;
  .text : { *(.text) }
  . = ALIGN(0x1000);
  .data : { *(.data) data_end = .; }
  script_uses = d_mul + 1;
}
",
    )
    .unwrap();
    let mut args = vec!["-static", "-T", "t.ld", "a.o", "--defsym=d_end=data_end-4"];
    args.extend_from_slice(DEFSYMS);
    compare_defsyms(&dir, &args);
}

/// Relocatable output: values relative to sections or absolute, and copied
/// types, as GNU ld writes them.
#[test]
fn defsym_expressions_in_relocatable_output() {
    require_tools!();
    let dir = scratch("defsym-relocatable");
    assemble(&dir, "a", DEFSYM_INPUT);
    compare_relocatable(
        &dir,
        &[
            "a.o",
            "--defsym=r_mul=fn*2",
            "--defsym=r_off=fn+4",
            "--defsym=r_alias=table",
            "--defsym=r_num=0x42",
            "--defsym=r_cond=DEFINED(nothing)?1:table_end",
        ],
    );
}

#[test]
fn defsym_syntax_errors_are_reported() {
    require_tools!();
    let dir = scratch("defsym-syntax");
    assemble(&dir, "a", DEFSYM_INPUT);
    let (ok, stderr) = qld_only(&dir, &["-static", "a.o", "--defsym=bad=fn+*2", "-o", "out"]);
    assert!(!ok, "a malformed --defsym links");
    assert!(stderr.contains("--defsym"), "{stderr}");
    assert!(!stderr.contains("not implemented"), "{stderr}");
}

/// Position-independent executables through the script engine (an
/// implicit script, `-Ttext`): the program headers outgrow GNU ld's first
/// `SIZEOF_HEADERS` estimate, and layout runs again with the real size, as
/// GNU ld's `ldelf_map_segments` does, instead of failing. The text
/// addresses are GNU ld's. (The dynamic sections themselves differ from
/// GNU ld's in size, which is not the script engine's doing.)
#[test]
fn pie_program_headers_outgrowing_the_estimate() {
    require_tools!();
    let dir = scratch("pie-headers");
    assemble(
        &dir,
        "start",
        "\t.text\n\t.globl _start\n_start:\n\tlea x_sym(%rip), %rax\n\tret\n",
    );
    fs::write(dir.join("extra.ld"), "x_sym = 1;\n").unwrap();
    let gnu = comparable_gnu_ld();
    for extra in ["extra.ld", "-Ttext=0x2000"] {
        let mut args = vec!["-pie", "--dynamic-linker=/lib/ld.so", "start.o", extra];
        if extra.starts_with("-T") {
            args.push("--defsym=x_sym=1");
        }
        let mut qld_args = args.clone();
        qld_args.extend(["-o", "qld.out"]);
        let (ok, stderr) = qld_only(&dir, &qld_args);
        assert!(ok, "{extra}: {stderr}");
        let headers = stdout_ok(&dir, "readelf", &["-lW", "qld.out"]);
        let count = headers
            .lines()
            .filter(|l| {
                let l = l.trim_start();
                l.starts_with("LOAD")
                    || l.starts_with("PHDR")
                    || l.starts_with("GNU_")
                    || l.starts_with("INTERP")
                    || l.starts_with("DYNAMIC")
                    || l.starts_with("NOTE")
            })
            .count();
        let phdr = headers
            .lines()
            .find(|l| l.trim_start().starts_with("PHDR"))
            .unwrap_or_else(|| panic!("{extra}: no PT_PHDR:\n{headers}"));
        let size = phdr.split_whitespace().nth(4).unwrap_or_default();
        assert_eq!(
            u64::from_str_radix(size.trim_start_matches("0x"), 16).unwrap(),
            56 * count as u64,
            "{extra}: {headers}"
        );
        if let Some(ld) = &gnu {
            let mut gnu_args = args.clone();
            gnu_args.extend(["-o", "gnu.out"]);
            assert!(run(&dir, ld, &gnu_args).status.success());
            let text = |file: &str| {
                stdout_ok(&dir, "readelf", &["-SW", file])
                    .lines()
                    .find(|l| l.contains(" .text "))
                    .map(|l| {
                        l.split(']')
                            .nth(1)
                            .unwrap_or("")
                            .split_whitespace()
                            .nth(2)
                            .unwrap_or("")
                            .to_string()
                    })
                    .unwrap_or_default()
            };
            assert_eq!(text("gnu.out"), text("qld.out"), "{extra}: .text address");
        }
    }
}

// ---------------------------------------------------------------------------
// Symbol table conventions: bindings, file symbols.
// ---------------------------------------------------------------------------

/// `.symtab` as sorted `name type binding visibility` lines, file symbols
/// included (the unnamed one as `<none>`); values and section indexes
/// differ between the linkers' layouts and are left out.
fn symtab_lines(dir: &Path, file: &str) -> Vec<String> {
    let text = stdout_ok(dir, "readelf", &["-sW", file]);
    let mut out: Vec<String> = text
        .lines()
        .skip_while(|l| !l.contains("'.symtab'"))
        .filter_map(|l| {
            let f: Vec<&str> = l.split_whitespace().collect();
            if f.len() < 7 || !f[0].ends_with(':') || f[3] == "SECTION" || f[0] == "0:" {
                return None;
            }
            Some(format!(
                "{} {} {} {}",
                f.get(7).copied().unwrap_or("<none>"),
                f[3],
                f[4],
                f[5]
            ))
        })
        .collect();
    out.sort();
    out
}

/// GNU ld keeps hidden symbols of input objects global in executables,
/// makes them local in shared objects, always makes the hidden symbols it
/// and linker scripts define local (without visibility, after an unnamed
/// file symbol), adds a file symbol named after each input without one,
/// and always defines `_edata`, `__bss_start` and `_end` in executables and
/// `_DYNAMIC` in dynamic outputs.
#[test]
fn symbol_table_bindings_like_gnu_ld() {
    require_tools!();
    let Some(ld) = comparable_gnu_ld() else {
        println!("SKIPPED: no GNU ld 2.44 or newer to compare against");
        return;
    };
    let dir = scratch("symtab-bindings");
    fs::create_dir_all(dir.join("sub")).unwrap();
    assemble(
        &dir,
        "sub/x",
        "\t.text\n\t.globl _start\n_start:\n\tlea hidden_fn(%rip), %rax\n\tlea __ehdr_start(%rip), %rax\n\tlea script_hidden(%rip), %rax\n\tcall local_fn\n\tret\nlocal_fn:\n\tret\n",
    );
    assemble(
        &dir,
        "y",
        "\t.file \"y.c\"\n\t.text\n\t.globl hidden_fn\n\t.hidden hidden_fn\n\t.type hidden_fn, @function\nhidden_fn:\n\tret\n\t.size hidden_fn, 1\n\t.globl prot_fn\n\t.protected prot_fn\nprot_fn:\n\tret\n\t.data\n\t.globl hidden_data\n\t.hidden hidden_data\nhidden_data:\n\t.long 1\nylocal:\n\t.long 2\n",
    );
    fs::write(dir.join("hide.ld"), "HIDDEN(script_hidden = 0x10);\n").unwrap();
    let cases: &[&[&str]] = &[
        &["-static", "sub/x.o", "y.o", "hide.ld"],
        &[
            "-pie",
            "--dynamic-linker=/lib/ld.so",
            "sub/x.o",
            "y.o",
            "hide.ld",
        ],
        &["-shared", "sub/x.o", "y.o", "hide.ld"],
        &["-r", "sub/x.o", "y.o"],
    ];
    for args in cases {
        for (linker, out) in [(&ld, "gnu.out"), (&qld_path(), "qld.out")] {
            let mut full = args.to_vec();
            full.extend(["-o", out]);
            let result = run(&dir, linker, &full);
            assert!(
                result.status.success(),
                "{} {}: {}",
                linker.display(),
                full.join(" "),
                String::from_utf8_lossy(&result.stderr)
            );
        }
        assert_eq!(
            symtab_lines(&dir, "gnu.out"),
            symtab_lines(&dir, "qld.out"),
            "symbol tables differ for {}",
            args.join(" ")
        );
    }
}