nanoflash 0.1.0

Lay out the flash of ESP32 and Arduino boards and write firmware to them through their bootloaders, natively or in the browser over Web Serial.
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
// ELF as the System V gABI and the ELF specification describe it; the parsing is `object`'s,
// written for nanoflash, no code taken from elsewhere.
//! Reading the loadable segments of an ELF file into the flat image they describe.
//!
//! A firmware linked for the flash stores each `PT_LOAD` segment with file data at its load
//! address (`p_paddr`: `.data` sits in the flash at its load address, and is copied to RAM at
//! start-up). The decoder turns them into the bytes from the lowest to the highest, `0xFF` in the
//! gaps, so every protocol writes an ELF as it writes an Intel HEX image. It is `no_std`, and the
//! image's allocation is fallible, made after its span is checked.

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

use object::elf::{FileHeader32, FileHeader64, PT_LOAD, SHF_ALLOC, SHT_NOBITS};
use object::read::elf::{FileHeader, ProgramHeader, SectionHeader};
use object::{Endianness, FileKind};
use serde::Serialize;

/// A segment of an ELF file, by the addresses it occupies.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ElfSegment {
    /// The load address of its first byte.
    pub start: u64,
    /// The load address after its last byte.
    pub end: u64,
    /// The names of the sections whose address range lies in the segment, comma separated, else
    /// `segment <index>`.
    pub sections: String,
}

/// The flat image an ELF file describes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElfImage {
    /// The lowest load address of a segment written.
    pub start: u64,
    /// The bytes from `start` up to the highest address of a segment written, `0xFF` in the gaps.
    pub bytes: Vec<u8>,
    /// The segments with data that are not part of the image (`skip_from`).
    pub skipped: Vec<ElfSegment>,
}

/// Why an ELF file cannot be decoded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ElfError {
    /// The file is not valid, or cannot be written to the flash as it is.
    Invalid {
        /// What is wrong.
        message: String,
    },
    /// There is not enough memory for the image.
    OutOfMemory {
        /// The size of the image in bytes.
        size: u64,
    },
}

impl ElfError {
    fn invalid(message: impl Into<String>) -> Self {
        ElfError::Invalid {
            message: message.into(),
        }
    }

    fn unreadable(error: object::Error) -> Self {
        ElfError::invalid(format!("it is not an ELF file that can be read: {error}"))
    }
}

impl fmt::Display for ElfError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ElfError::Invalid { message } => formatter.write_str(message),
            ElfError::OutOfMemory { size } => {
                write!(formatter, "there is not enough memory for 0x{size:x} bytes")
            }
        }
    }
}

/// Where the image may be, and how big.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElfWindow {
    /// The lowest address a segment may start at.
    pub start: u64,
    /// The address after the highest byte a segment may reach.
    pub end: u64,
    /// The most bytes the image may span, from its lowest to its highest byte.
    pub maximum_span: u64,
    /// Segments at or above this address are not part of the image and are reported in
    /// [`ElfImage::skipped`] (the data, EEPROM, fuse and lock spaces of avr-gcc, from
    /// `0x800000`).
    pub skip_from: Option<u64>,
}

/// The most section names given for a segment.
const MAXIMUM_NAMES: usize = 8;
/// The most bytes of a section name kept.
const MAXIMUM_NAME_BYTES: usize = 32;
/// The most skipped segments given section names; the others are named by their index, so that
/// the work stays linear in the size of the file.
const MAXIMUM_NAMED_SKIPPED: usize = 16;

/// A loaded section that has an address: what names a segment in a message.
struct NamedSection {
    start: u64,
    end: u64,
    name: String,
}

/// A `PT_LOAD` segment with data.
struct Loaded<'a> {
    index: usize,
    start: u64,
    end: u64,
    virtual_start: u64,
    virtual_end: u64,
    data: &'a [u8],
}

impl Loaded<'_> {
    /// The names of the sections whose address range lies in the segment, at most
    /// `MAXIMUM_NAMES` of at most `MAXIMUM_NAME_BYTES` bytes each, else `segment <index>`.
    ///
    /// Sections are placed by their virtual address, the segment's `p_vaddr`. Only segments that
    /// end up in a message or in the skipped list are named, so that a hostile file cannot make
    /// the names grow with the product of its segments and sections.
    fn names(&self, sections: &[NamedSection]) -> String {
        let mut names = String::new();
        let mut count = 0usize;
        for section in sections {
            if section.start < self.virtual_start || section.end > self.virtual_end {
                continue;
            }
            if count == MAXIMUM_NAMES {
                names.push_str(",...");
                break;
            }
            if count > 0 {
                names.push(',');
            }
            names.push_str(&section.name);
            count += 1;
        }
        if names.is_empty() {
            names = format!("segment {}", self.index);
        }
        names
    }

    fn describe(&self, sections: &[NamedSection]) -> ElfSegment {
        ElfSegment {
            start: self.start,
            end: self.end,
            sections: self.names(sections),
        }
    }
}

/// What a file's segments and sections give.
struct Collected<'a> {
    segments: Vec<Loaded<'a>>,
    sections: Vec<NamedSection>,
}

/// Appends `item` to `vector`, or says there is not enough memory.
fn push<T>(vector: &mut Vec<T>, item: T) -> Result<(), ElfError> {
    vector.try_reserve(1).map_err(|_| ElfError::OutOfMemory {
        size: (vector.len() as u64)
            .saturating_add(1)
            .saturating_mul(core::mem::size_of::<T>() as u64),
    })?;
    vector.push(item);
    Ok(())
}

/// Checks that the headers of `bytes` parse, and that every `PT_LOAD` segment and every section
/// has its data in the file.
///
/// # Errors
///
/// [`ElfError::Invalid`] naming what cannot be read.
pub fn validate_elf(bytes: &[u8]) -> Result<(), ElfError> {
    match FileKind::parse(bytes).map_err(ElfError::unreadable)? {
        FileKind::Elf32 => validate::<FileHeader32<Endianness>>(bytes),
        FileKind::Elf64 => validate::<FileHeader64<Endianness>>(bytes),
        _ => Err(ElfError::invalid(
            "it is not an ELF file that can be read: it is another kind of file",
        )),
    }
}

fn validate<Elf: FileHeader<Endian = Endianness>>(bytes: &[u8]) -> Result<(), ElfError> {
    let header = Elf::parse(bytes).map_err(ElfError::unreadable)?;
    let endian = header.endian().map_err(ElfError::unreadable)?;
    let segments = header
        .program_headers(endian, bytes)
        .map_err(ElfError::unreadable)?;
    for (index, segment) in segments.iter().enumerate() {
        if segment.p_type(endian) == PT_LOAD {
            segment.data(endian, bytes).map_err(|()| {
                ElfError::invalid(format!(
                    "it is not an ELF file that can be read: the data of the segment at 0x{:x} (segment {index}) is not in the file",
                    segment.p_paddr(endian).into()
                ))
            })?;
        }
    }
    let sections = header
        .sections(endian, bytes)
        .map_err(ElfError::unreadable)?;
    for section in sections.iter() {
        section
            .data(endian, bytes)
            .map_err(|error| {
                ElfError::invalid(format!(
                    "it is not an ELF file that can be read: the data of the section at 0x{:x}: {error}",
                    section.sh_addr(endian).into()
                ))
            })?;
    }
    Ok(())
}

/// Whether `bytes` start an ELF file made for an AVR chip (`e_machine` 83), whose segments from
/// `0x800000` are the data, EEPROM, fuse, lock and signature spaces of avr-gcc, not the flash.
pub fn is_avr_elf(bytes: &[u8]) -> bool {
    const EM_AVR: u16 = 83;
    if !super::is_elf(bytes) {
        return false;
    }
    let machine = bytes
        .get(18..20)
        .and_then(|field| <[u8; 2]>::try_from(field).ok());
    match (bytes.get(5), machine) {
        (Some(1), Some(field)) => u16::from_le_bytes(field) == EM_AVR,
        (Some(2), Some(field)) => u16::from_be_bytes(field) == EM_AVR,
        _ => false,
    }
}

/// Reads the `PT_LOAD` segments with data of `bytes` into the flat image they describe.
///
/// # Errors
///
/// [`ElfError::Invalid`] when the file cannot be read, has no segment to load, has overlapping
/// segments, a segment outside `window`, or segments that span more than `window.maximum_span`;
/// [`ElfError::OutOfMemory`] when the image cannot be allocated.
pub fn decode_elf(bytes: &[u8], window: &ElfWindow) -> Result<ElfImage, ElfError> {
    let collected = match FileKind::parse(bytes).map_err(ElfError::unreadable)? {
        FileKind::Elf32 => collect::<FileHeader32<Endianness>>(bytes)?,
        FileKind::Elf64 => collect::<FileHeader64<Endianness>>(bytes)?,
        _ => {
            return Err(ElfError::invalid(
                "it is not an ELF file that can be read: it is another kind of file",
            ));
        }
    };
    let Collected { segments, sections } = collected;
    let mut skipped = Vec::new();
    let mut written = Vec::new();
    for segment in segments {
        if window.skip_from.is_some_and(|from| segment.start >= from) {
            let names: &[NamedSection] = if skipped.len() < MAXIMUM_NAMED_SKIPPED {
                &sections
            } else {
                &[]
            };
            push(&mut skipped, segment.describe(names))?;
        } else {
            push(&mut written, segment)?;
        }
    }
    for segment in &written {
        if segment.start < window.start || segment.end > window.end {
            return Err(ElfError::invalid(format!(
                "its segment 0x{:x}..0x{:x} ({}) is outside the flash, mapped at 0x{:x}..0x{:x}: link it for the flash (memory.x), or fix the base address of the layout",
                segment.start,
                segment.end,
                segment.names(&sections),
                window.start,
                window.end
            )));
        }
    }
    // Segments with equal keys are refused as an overlap below, so the sort needs no stability.
    // An unstable sort works in place: it makes no allocation that the input would size.
    written.sort_unstable_by_key(|segment| (segment.start, segment.end));
    for pair in written.windows(2) {
        if let [first, second] = pair
            && second.start < first.end
        {
            return Err(ElfError::invalid(format!(
                "its segments 0x{:x}..0x{:x} ({}) and 0x{:x}..0x{:x} ({}) overlap",
                first.start,
                first.end,
                first.names(&sections),
                second.start,
                second.end,
                second.names(&sections)
            )));
        }
    }
    let (Some(first), Some(last)) = (written.first(), written.last()) else {
        return Err(ElfError::invalid(
            "it has no segment to load (no PT_LOAD segment with data)",
        ));
    };
    let start = first.start;
    // Sorted and without overlap: the last segment ends highest.
    let end = last.end;
    let span = end.checked_sub(start).ok_or_else(|| {
        ElfError::invalid(format!(
            "its segments 0x{start:x}..0x{end:x} are not in increasing order"
        ))
    })?;
    if span > window.maximum_span {
        return Err(ElfError::invalid(format!(
            "its segments span 0x{start:x}..0x{end:x}, 0x{span:x} bytes, more than the 0x{:x} bytes it may span",
            window.maximum_span
        )));
    }
    let size = usize::try_from(span).map_err(|_| ElfError::OutOfMemory { size: span })?;
    let mut image = Vec::new();
    image
        .try_reserve_exact(size)
        .map_err(|_| ElfError::OutOfMemory { size: span })?;
    image.resize(size, 0xFF);
    for segment in &written {
        // Inside the span, which fits in memory.
        let offset = segment
            .start
            .checked_sub(start)
            .and_then(|offset| usize::try_from(offset).ok())
            .ok_or(ElfError::OutOfMemory { size: span })?;
        if let Some(target) = image
            .get_mut(offset..)
            .and_then(|rest| rest.get_mut(..segment.data.len()))
        {
            target.copy_from_slice(segment.data);
        }
    }
    Ok(ElfImage {
        start,
        bytes: image,
        skipped,
    })
}

/// The `PT_LOAD` segments with file data, at their physical address.
fn collect<Elf: FileHeader<Endian = Endianness>>(bytes: &[u8]) -> Result<Collected<'_>, ElfError> {
    let header = Elf::parse(bytes).map_err(ElfError::unreadable)?;
    let endian = header.endian().map_err(ElfError::unreadable)?;
    let segments = header
        .program_headers(endian, bytes)
        .map_err(ElfError::unreadable)?;
    // Section names are for messages only: a file whose section headers cannot be read is still
    // loaded.
    let mut named = Vec::new();
    if let Ok(table) = header.sections(endian, bytes) {
        for section in table.iter() {
            let start: u64 = section.sh_addr(endian).into();
            let size: u64 = section.sh_size(endian).into();
            if section.sh_flags(endian).0 & SHF_ALLOC.0 == 0
                || section.sh_type(endian) == SHT_NOBITS
                || size == 0
            {
                continue;
            }
            let (Some(end), Ok(name)) =
                (start.checked_add(size), table.section_name(endian, section))
            else {
                continue;
            };
            let name = name.get(..MAXIMUM_NAME_BYTES).unwrap_or(name);
            push(
                &mut named,
                NamedSection {
                    start,
                    end,
                    name: String::from_utf8_lossy(name).into_owned(),
                },
            )?;
        }
    }
    let mut loaded = Vec::new();
    for (index, segment) in segments.iter().enumerate() {
        if segment.p_type(endian) != PT_LOAD {
            continue;
        }
        let file_size: u64 = segment.p_filesz(endian).into();
        if file_size == 0 {
            continue;
        }
        let address: u64 = segment.p_paddr(endian).into();
        let data = segment.data(endian, bytes).map_err(|()| {
            ElfError::invalid(format!(
                "it is not an ELF file that can be read: the data of the segment at 0x{address:x} (segment {index}) is not in the file"
            ))
        })?;
        let end = address.checked_add(file_size).ok_or_else(|| {
            ElfError::invalid(format!(
                "its segment at 0x{address:x} (segment {index}) ends beyond the 64-bit address space"
            ))
        })?;
        let virtual_start: u64 = segment.p_vaddr(endian).into();
        // A virtual range that wraps is as large as the address space can hold.
        let virtual_end = virtual_start.saturating_add(segment.p_memsz(endian).into());
        push(
            &mut loaded,
            Loaded {
                index,
                start: address,
                end,
                virtual_start,
                virtual_end,
                data,
            },
        )?;
    }
    Ok(Collected {
        segments: loaded,
        sections: named,
    })
}

/// The test writer of ELF files, shared with the tests of the modules that read ELF images.
///
/// Written by hand, not with `object::write::elf::Writer`: the tests control every field and
/// write 64-bit and big-endian files, which that writer's two-phase reservation makes longer.
#[cfg(test)]
pub(crate) mod writer {
    use alloc::vec;
    use alloc::vec::Vec;

    pub(crate) const PT_LOAD: u32 = 1;
    pub(crate) const PT_NOTE: u32 = 4;
    pub(crate) const EM_ARM: u16 = 40;
    pub(crate) const EM_AVR: u16 = 83;
    pub(crate) const EM_XTENSA: u16 = 94;

    /// One program header and, when it has a name, the section that goes with it.
    #[derive(Clone)]
    pub(crate) struct Segment<'a> {
        pub(crate) p_type: u32,
        pub(crate) paddr: u64,
        pub(crate) vaddr: u64,
        pub(crate) data: &'a [u8],
        pub(crate) memsz: u64,
        pub(crate) name: &'a str,
        pub(crate) flags: &'a str,
    }

    pub(crate) fn segment<'a>(
        paddr: u64,
        vaddr: u64,
        data: &'a [u8],
        memsz: u64,
        name: &'a str,
        flags: &'a str,
    ) -> Segment<'a> {
        Segment {
            p_type: PT_LOAD,
            paddr,
            vaddr,
            data,
            memsz,
            name,
            flags,
        }
    }

    /// A load segment whose section sits at the same address.
    pub(crate) fn simple<'a>(address: u64, data: &'a [u8], name: &'a str) -> Segment<'a> {
        segment(address, address, data, data.len() as u64, name, "AX")
    }

    /// Writes an `ET_EXEC` file: the test writer.
    ///
    /// Written by hand rather than through a library, so that the tests control every field and
    /// can produce 64-bit and big-endian files too.
    pub(crate) fn write_elf(
        is_64: bool,
        big_endian: bool,
        machine: u16,
        entry: u64,
        segments: &[Segment<'_>],
    ) -> Vec<u8> {
        struct Out {
            bytes: Vec<u8>,
            big: bool,
        }
        impl Out {
            fn u16(&mut self, value: u16) {
                let b = if self.big {
                    value.to_be_bytes()
                } else {
                    value.to_le_bytes()
                };
                self.bytes.extend_from_slice(&b);
            }
            fn u32(&mut self, value: u32) {
                let b = if self.big {
                    value.to_be_bytes()
                } else {
                    value.to_le_bytes()
                };
                self.bytes.extend_from_slice(&b);
            }
            fn u64(&mut self, value: u64) {
                let b = if self.big {
                    value.to_be_bytes()
                } else {
                    value.to_le_bytes()
                };
                self.bytes.extend_from_slice(&b);
            }
            fn word(&mut self, is_64: bool, value: u64) {
                if is_64 {
                    self.u64(value);
                } else {
                    self.u32(value as u32);
                }
            }
        }
        let header_size: u64 = if is_64 { 64 } else { 52 };
        let program_size: u64 = if is_64 { 56 } else { 32 };
        let section_size: u64 = if is_64 { 64 } else { 40 };
        let named: Vec<&Segment<'_>> = segments.iter().filter(|s| !s.name.is_empty()).collect();

        // File layout: header, program headers, segment data, section names, section headers.
        let mut offset = header_size + program_size * segments.len() as u64;
        let mut data_offsets = Vec::new();
        for segment in segments {
            data_offsets.push(offset);
            offset += segment.data.len() as u64;
        }
        let mut names = vec![0u8];
        let mut name_offsets = Vec::new();
        for segment in &named {
            name_offsets.push(names.len() as u32);
            names.extend_from_slice(segment.name.as_bytes());
            names.push(0);
        }
        let shstrtab_name = names.len() as u32;
        names.extend_from_slice(b".shstrtab\0");
        let names_offset = offset;
        offset += names.len() as u64;
        let section_headers_offset = offset;
        let section_count = named.len() as u16 + 2;

        let mut out = Out {
            bytes: Vec::new(),
            big: big_endian,
        };
        out.bytes
            .extend_from_slice(&[0x7f, b'E', b'L', b'F', if is_64 { 2 } else { 1 }]);
        out.bytes.push(if big_endian { 2 } else { 1 });
        out.bytes.push(1);
        out.bytes.resize(16, 0);
        out.u16(2);
        out.u16(machine);
        out.u32(1);
        out.word(is_64, entry);
        out.word(is_64, header_size);
        out.word(is_64, section_headers_offset);
        out.u32(0);
        out.u16(header_size as u16);
        out.u16(program_size as u16);
        out.u16(segments.len() as u16);
        out.u16(section_size as u16);
        out.u16(section_count);
        out.u16(section_count - 1);

        for (segment, data_offset) in segments.iter().zip(&data_offsets) {
            let flags = 4 | if segment.flags.contains('X') { 1 } else { 0 };
            let flags = flags | if segment.flags.contains('W') { 2 } else { 0 };
            if is_64 {
                out.u32(segment.p_type);
                out.u32(flags);
                out.u64(*data_offset);
                out.u64(segment.vaddr);
                out.u64(segment.paddr);
                out.u64(segment.data.len() as u64);
                out.u64(segment.memsz);
                out.u64(4);
            } else {
                out.u32(segment.p_type);
                out.u32(*data_offset as u32);
                out.u32(segment.vaddr as u32);
                out.u32(segment.paddr as u32);
                out.u32(segment.data.len() as u32);
                out.u32(segment.memsz as u32);
                out.u32(flags);
                out.u32(4);
            }
        }
        for segment in segments {
            out.bytes.extend_from_slice(segment.data);
        }
        out.bytes.extend_from_slice(&names);

        let section = |out: &mut Out,
                       name: u32,
                       kind: u32,
                       flags: u64,
                       address: u64,
                       offset: u64,
                       size: u64| {
            out.u32(name);
            out.u32(kind);
            out.word(is_64, flags);
            out.word(is_64, address);
            out.word(is_64, offset);
            out.word(is_64, size);
            out.u32(0);
            out.u32(0);
            out.word(is_64, 4);
            out.word(is_64, 0);
        };
        section(&mut out, 0, 0, 0, 0, 0, 0);
        for (segment, name_offset) in named.iter().zip(&name_offsets) {
            let index = segments
                .iter()
                .position(|candidate| core::ptr::eq(candidate, *segment))
                .unwrap();
            let nobits = segment.data.is_empty();
            let mut flags = 2u64;
            if segment.flags.contains('X') {
                flags |= 4;
            }
            if segment.flags.contains('W') {
                flags |= 1;
            }
            section(
                &mut out,
                *name_offset,
                if nobits { 8 } else { 1 },
                flags,
                segment.vaddr,
                data_offsets[index],
                if nobits {
                    segment.memsz
                } else {
                    segment.data.len() as u64
                },
            );
        }
        section(
            &mut out,
            shstrtab_name,
            3,
            0,
            0,
            names_offset,
            names.len() as u64,
        );
        out.bytes
    }

    pub(crate) fn elf32(machine: u16, entry: u64, segments: &[Segment<'_>]) -> Vec<u8> {
        write_elf(false, false, machine, entry, segments)
    }
}

#[cfg(test)]
mod tests {
    use super::writer::*;
    use super::*;
    use alloc::string::ToString;
    use alloc::vec;
    use proptest::collection::vec as proptest_vec;
    use proptest::prelude::*;
    use std::path::PathBuf;

    const APPLICATION_BIN: &[u8] = include_bytes!("../../tests/images/application.bin");
    /// A committed fixture, read at run time so that the test that rewrites them can build before
    /// they exist.
    fn fixture(name: &str) -> Vec<u8> {
        std::fs::read(
            PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/images")
                .join(name),
        )
        .unwrap()
    }

    fn window(start: u64, end: u64) -> ElfWindow {
        ElfWindow {
            start,
            end,
            maximum_span: 0x200_0000,
            skip_from: None,
        }
    }

    fn application_segments() -> Vec<Segment<'static>> {
        vec![
            segment(
                0x10000,
                0x10000,
                &APPLICATION_BIN[..0x1000],
                0x1000,
                ".text",
                "AX",
            ),
            segment(
                0x11000,
                0x2000_0000,
                &APPLICATION_BIN[0x1000..],
                0x1000,
                ".data",
                "WA",
            ),
            segment(0x12000, 0x2000_1000, &[], 0x100, ".bss", "WA"),
            Segment {
                p_type: PT_NOTE,
                paddr: 0,
                vaddr: 0,
                data: &[],
                memsz: 0,
                name: "",
                flags: "",
            },
        ]
    }

    fn avr_hex_image() -> Vec<u8> {
        let hex = include_bytes!("../../tests/images/avr-application.hex");
        crate::flash::decode_intel_hex(hex, 0x10_0000)
            .unwrap()
            .bytes
    }

    fn esp32s3_segments() -> Vec<Segment<'static>> {
        static BYTES: [u8; 64] = {
            let mut bytes = [0u8; 64];
            let mut index = 0;
            while index < 64 {
                bytes[index] = index as u8;
                index += 1;
            }
            bytes
        };
        vec![
            segment(0x3C00_0020, 0x3C00_0020, &BYTES, 64, ".flash.rodata", "A"),
            segment(0x4200_0020, 0x4200_0020, &BYTES, 64, ".flash.text", "AX"),
            segment(
                0x4037_8000,
                0x4037_8000,
                &BYTES[..32],
                32,
                ".iram0.text",
                "AX",
            ),
            segment(
                0x3FC8_8000,
                0x3FC8_8000,
                &BYTES[..16],
                16,
                ".dram0.data",
                "WA",
            ),
        ]
    }

    fn fixture_files() -> Vec<(&'static str, Vec<u8>)> {
        let mut avr = vec![simple(0, &[], ".text")];
        let image = avr_hex_image();
        avr[0].data = &image;
        avr[0].memsz = image.len() as u64;
        let eeprom = [1u8, 2, 3, 4];
        avr.push(segment(0x81_0000, 0x81_0000, &eeprom, 4, ".eeprom", "WA"));
        vec![
            (
                "application.elf",
                elf32(EM_ARM, 0x10101, &application_segments()),
            ),
            (
                "avr-application.elf",
                write_elf(false, false, EM_AVR, 0, &avr),
            ),
            (
                "esp32s3-application.elf",
                elf32(EM_XTENSA, 0x4037_8000, &esp32s3_segments()),
            ),
        ]
    }

    #[test]
    fn committed_fixtures_are_current() {
        let directory = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/images");
        for (name, bytes) in fixture_files() {
            let path = directory.join(name);
            if std::env::var_os("NANOFLASH_UPDATE_FIXTURES").is_some() {
                std::fs::write(&path, &bytes).unwrap();
            }
            let committed = std::fs::read(&path).unwrap();
            assert!(
                committed == bytes,
                "{name} is out of date: run with NANOFLASH_UPDATE_FIXTURES=1"
            );
        }
    }

    #[test]
    fn loads_segments_at_their_physical_address() {
        let image = decode_elf(&fixture("application.elf"), &window(0, 0x10_0000)).unwrap();
        assert_eq!(
            (image.start, image.bytes.as_slice()),
            (0x10000, APPLICATION_BIN)
        );
        assert!(image.skipped.is_empty());
    }

    #[test]
    fn gaps_read_as_erased_flash() {
        let file = elf32(
            EM_ARM,
            0,
            &[
                simple(0x10000, &[1, 2, 3, 4], ".a"),
                simple(0x10008, &[5, 6, 7, 8], ".b"),
            ],
        );
        let image = decode_elf(&file, &window(0, 0x10_0000)).unwrap();
        assert_eq!(image.start, 0x10000);
        assert_eq!(
            image.bytes,
            [1, 2, 3, 4, 0xFF, 0xFF, 0xFF, 0xFF, 5, 6, 7, 8]
        );
    }

    #[test]
    fn avr_spaces_are_skipped() {
        let options = ElfWindow {
            skip_from: Some(0x80_0000),
            ..window(0, 0x8000)
        };
        let image = decode_elf(&fixture("avr-application.elf"), &options).unwrap();
        assert_eq!(image.start, 0);
        assert_eq!(image.bytes, avr_hex_image());
        assert_eq!(
            image.skipped,
            [ElfSegment {
                start: 0x81_0000,
                end: 0x81_0004,
                sections: ".eeprom".into()
            }]
        );
        // Without the skip, the EEPROM segment is outside the flash.
        let error = decode_elf(&fixture("avr-application.elf"), &window(0, 0x8000)).unwrap_err();
        assert!(error.to_string().contains("0x810000"), "{error}");
    }

    fn message(file: &[u8], options: &ElfWindow) -> String {
        decode_elf(file, options).unwrap_err().to_string()
    }

    #[test]
    fn refusals_name_sections_and_addresses() {
        let overlap = elf32(
            EM_ARM,
            0,
            &[
                simple(0x10000, &[0; 0x10], ".a"),
                simple(0x10008, &[0; 0x10], ".b"),
            ],
        );
        let text = message(&overlap, &window(0, 0x10_0000));
        assert!(text.contains("0x10000..0x10010 (.a)"), "{text}");
        assert!(text.contains("0x10008..0x10018 (.b)"), "{text}");
        assert!(text.contains("overlap"), "{text}");

        let ram = elf32(
            EM_ARM,
            0,
            &[segment(0x2000_0000, 0x2000_0000, &[1; 4], 4, ".data", "WA")],
        );
        let text = message(&ram, &window(0, 0x10_0000));
        assert!(text.contains("0x20000000"), "{text}");
        assert!(text.contains("(.data)"), "{text}");
        assert!(text.contains("outside the flash"), "{text}");

        let low = elf32(EM_ARM, 0, &[simple(0x1000, &[1; 4], ".text")]);
        let text = message(&low, &window(0x800_0000, 0x810_0000));
        assert!(
            text.contains("outside the flash, mapped at 0x8000000..0x8100000"),
            "{text}"
        );

        let wide = elf32(
            EM_ARM,
            0,
            &[simple(0, &[1], ".a"), simple(0x200_0000, &[1], ".b")],
        );
        let text = message(&wide, &window(0, u64::MAX));
        assert!(
            text.contains("span 0x0..0x2000001, 0x2000001 bytes, more than the 0x2000000 bytes"),
            "{text}"
        );

        let bss = elf32(
            EM_ARM,
            0,
            &[segment(0x10000, 0x10000, &[], 0x100, ".bss", "WA")],
        );
        assert!(message(&bss, &window(0, 0x10_0000)).contains("no segment to load"));

        let text = message(b"\x7fELF", &window(0, 0x10_0000));
        assert!(text.starts_with("it is not an ELF file"), "{text}");
        assert!(message(&[], &window(0, 0x10_0000)).starts_with("it is not an ELF file"));
    }

    #[test]
    fn sections_are_named_by_virtual_address() {
        // The segments of the ARM fixture are placed at their physical address; the names come
        // from the virtual one, and a segment without a section is named by its index.
        let file = elf32(
            EM_ARM,
            0,
            &[
                segment(0x10000, 0x2000_0000, &[1; 4], 4, ".data", "WA"),
                segment(0x10010, 0x3000_0000, &[1; 4], 4, "", "WA"),
                simple(0x10008, &[2; 4], ".text"),
                simple(0x10010, &[2; 4], ".more"),
            ],
        );
        let text = message(&file, &window(0, 0x10_0000));
        assert!(text.contains("0x10010..0x10014 (segment 1)"), "{text}");
        let text = message(&file, &window(0x20000, 0x30000));
        assert!(text.contains("(.data)"), "{text}");
    }

    #[test]
    fn section_names_are_bounded() {
        // A segment that spans the address space, and many sections that share one long name:
        // the names of a message stay short, however many sections and segments there are.
        let long = "n".repeat(4000);
        let data = [1u8; 4];
        let mut segments = vec![
            segment(0x100, 0x100, &data, 0xFFFF_FFFF, ".text", "AX"),
            segment(0x10000, 0, &data, 0xFFFF_FFFF, "", "AX"),
        ];
        for index in 0..200u64 {
            segments.push(segment(
                0x20000 + index * 4,
                0x1000 + index * 4,
                &data,
                4,
                &long,
                "AX",
            ));
        }
        let file = write_elf(false, false, EM_ARM, 0, &segments);
        let options = ElfWindow {
            skip_from: Some(0x10000),
            ..window(0, 0x1000)
        };
        let image = decode_elf(&file, &options).unwrap();
        let text = &image.skipped[0].sections;
        assert!(text.len() < 600, "{} bytes: {text}", text.len());
        assert!(text.ends_with(",..."), "{text}");
        assert!(text.contains(&"n".repeat(32)), "{text}");
        assert!(!text.contains(&"n".repeat(33)), "{text}");
        // The same names in an error message.
        let text = message(&file, &window(0, 0x10));
        assert!(text.len() < 600, "{} bytes: {text}", text.len());
        assert!(text.contains(",..."), "{text}");
    }

    #[test]
    fn only_the_first_skipped_segments_are_named() {
        // Many skipped segments, each with a section of its own: naming all of them would cost
        // their number times the number of sections.
        let data = [1u8; 4];
        let names: Vec<String> = (0..3000).map(|index| alloc::format!(".s{index}")).collect();
        let mut segments = vec![segment(0x100, 0x100, &data, 4, ".text", "AX")];
        for (index, name) in names.iter().enumerate() {
            let index = index as u64;
            segments.push(segment(
                0x10000 + index * 4,
                0x1000 + index * 4,
                &data,
                4,
                name,
                "AX",
            ));
        }
        let file = write_elf(false, false, EM_AVR, 0, &segments);
        let options = ElfWindow {
            skip_from: Some(0x10000),
            ..window(0, 0x1000)
        };
        let image = decode_elf(&file, &options).unwrap();
        assert_eq!(image.skipped.len(), 3000);
        for (index, segment) in image.skipped.iter().enumerate() {
            if index < 16 {
                assert_eq!(segment.sections, alloc::format!(".s{index}"));
            } else {
                assert_eq!(segment.sections, alloc::format!("segment {}", index + 1));
            }
        }
    }

    #[test]
    fn sixty_four_bit_and_big_endian_files_are_read() {
        let expected = decode_elf(&fixture("application.elf"), &window(0, 0x10_0000)).unwrap();
        for (is_64, big) in [(true, false), (false, true), (true, true)] {
            let file = write_elf(is_64, big, EM_ARM, 0x10101, &application_segments());
            assert_eq!(
                decode_elf(&file, &window(0, 0x10_0000)).unwrap(),
                expected,
                "64-bit {is_64}, big endian {big}"
            );
            validate_elf(&file).unwrap();
        }
    }

    #[test]
    fn the_espressif_fixture_is_valid() {
        let file = elf32(EM_XTENSA, 0x4037_8000, &esp32s3_segments());
        validate_elf(&file).unwrap();
        let text = message(&file, &window(0, 0x100_0000));
        assert!(text.contains("(.flash.rodata)"), "{text}");
    }

    #[test]
    fn validation_refuses_ranges_outside_the_file() {
        let mut file = elf32(EM_ARM, 0, &[simple(0x10000, &[1; 16], ".text")]);
        validate_elf(&file).unwrap();
        // The section headers and names are cut off: the file is not valid, but its segment is
        // still readable, as the names are for messages only.
        file.truncate(file.len() - 100);
        assert!(validate_elf(&file).is_err());
        assert!(decode_elf(&file, &window(0, 0x10_0000)).is_ok());
        // The data of the segment is cut off.
        file.truncate(52 + 32 + 8);
        assert!(validate_elf(&file).is_err());
        assert!(decode_elf(&file, &window(0, 0x10_0000)).is_err());
    }

    #[test]
    fn a_file_is_an_elf_by_its_magic() {
        assert!(crate::flash::is_elf(&fixture("application.elf")));
        assert!(!crate::flash::is_elf(b":10000000"));
        assert!(!crate::flash::is_elf(b""));
    }

    proptest! {
        #[test]
        fn arbitrary_bytes_never_panic(bytes in proptest_vec(any::<u8>(), 0..4096)) {
            let _ = decode_elf(&bytes, &window(0, 0x10_0000));
            let _ = validate_elf(&bytes);
        }

        #[test]
        fn mutated_fixtures_never_panic(
            index in any::<usize>(),
            value in any::<u8>(),
            truncate in any::<usize>(),
        ) {
            // Any byte of the file, section table included, and any length from 0 to the whole.
            let mut file = fixture("application.elf");
            let length = file.len();
            file[index % length] = value;
            file.truncate(truncate % (length + 1));
            let options = window(0, 0x10_0000);
            if let Ok(image) = decode_elf(&file, &options) {
                prop_assert!(image.bytes.len() as u64 <= options.maximum_span);
            }
            let _ = validate_elf(&file);
        }

        #[test]
        fn mutated_headers_never_panic(
            index in 0usize..0x200,
            value in any::<u8>(),
        ) {
            let mut file = fixture("application.elf");
            let index = index.min(file.len() - 1);
            file[index] = value;
            let options = window(0, u64::MAX);
            if let Ok(image) = decode_elf(&file, &options) {
                prop_assert!(image.bytes.len() as u64 <= options.maximum_span);
            }
            let _ = validate_elf(&file);
        }
    }

    #[test]
    fn avr_files_are_found_by_their_machine() {
        let avr = write_elf(false, false, EM_AVR, 0, &[simple(0, &[1; 4], ".text")]);
        assert!(is_avr_elf(&avr));
        let big_endian = write_elf(false, true, EM_AVR, 0, &[simple(0, &[1; 4], ".text")]);
        assert!(is_avr_elf(&big_endian));
        let arm = write_elf(false, false, EM_ARM, 0, &[simple(0, &[1; 4], ".text")]);
        assert!(!is_avr_elf(&arm));
        assert!(!is_avr_elf(&avr[..19]));
        assert!(!is_avr_elf(&[]));
        // The magic decides first: other bytes with the machine fields are not an ELF file.
        let mut other = avr.clone();
        other[0] = 0;
        assert!(!is_avr_elf(&other));
    }
}