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
use crate::util::{opt_u32, read_str, read_u32le, read_u8};
use crate::Patch;
use std::convert::TryInto;
use std::fmt::{self, Display, Formatter};
use std::io::{self, Read};

/// A section definition.
#[derive(Debug)]
pub struct Section {
    name: Vec<u8>,
    size: u32,
    sect_type: SectionType,
    modifier: SectionMod,
    org: Option<u32>,
    bank: Option<u32>,
    align: u8,
    ofs: u32,
}
impl Section {
    pub(crate) fn read_from(mut input: impl Read) -> Result<Self, io::Error> {
        let name = read_str(&mut input)?;
        let size = read_u32le(&mut input)?;
        let sect_type = read_u8(&mut input)?;
        let modifier = SectionMod::from(sect_type)?;
        let org = opt_u32(read_u32le(&mut input)?);
        let bank = opt_u32(read_u32le(&mut input)?);
        let align = read_u8(&mut input)?;
        let ofs = read_u32le(&mut input)?;

        let sect_type = SectionType::read_from(sect_type, input, size.try_into().unwrap())?;

        Ok(Self {
            name,
            size,
            sect_type,
            modifier,
            org,
            bank,
            align,
            ofs,
        })
    }

    /// The section's name.
    /// As with all names pulled from object files, this is not guaranteed to be valid UTF-8.
    pub fn name(&self) -> &[u8] {
        &self.name
    }

    /// The section's size.
    pub fn size(&self) -> u32 {
        self.size
    }

    /// The section's memory type, including data, if any.
    pub fn type_data(&self) -> &SectionType {
        &self.sect_type
    }

    /// The section's modifier (regular, union, etc.).
    pub fn modifier(&self) -> SectionMod {
        self.modifier
    }

    /// The address at which the section was fixed, or `None` if left floating.
    pub fn org(&self) -> Option<u32> {
        self.org
    }

    /// The bank the section was assigned, or `None` if left floating.
    pub fn bank(&self) -> Option<u32> {
        self.bank
    }

    /// The section's alignment, in bits. 0 if not specified.
    pub fn align(&self) -> u8 {
        self.align
    }

    /// The section's alignment offset.
    pub fn align_ofs(&self) -> u32 {
        self.ofs
    }
}

/// A section memory type, and associated data if applicable.
#[derive(Debug)]
pub enum SectionType {
    Wram0,
    Vram,
    Romx(SectionData),
    Rom0(SectionData),
    Hram,
    Wramx,
    Sram,
    Oam,
}
impl SectionType {
    fn read_from(byte: u8, input: impl Read, size: usize) -> Result<Self, io::Error> {
        use SectionType::*;

        Ok(match byte & 0x3F {
            0 => Wram0,
            1 => Vram,
            2 => Romx(SectionData::read_from(input, size)?),
            3 => Rom0(SectionData::read_from(input, size)?),
            4 => Hram,
            5 => Wramx,
            6 => Sram,
            7 => Oam,
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "Invalid section type",
                ))
            }
        })
    }

    /// The [section][Section]'s ROM data, if any.
    pub fn data(&self) -> Option<&SectionData> {
        use SectionType::*;

        match self {
            Rom0(data) | Romx(data) => Some(&data),
            _ => None,
        }
    }

    /// Returns whether the section type may be banked.
    /// Note that it's possible to configure this in RGBLINK (disabling VRAM banking with `-d`, for
    /// example), so this may return `true` but have RGBLINK say otherwise.
    pub fn is_banked(&self) -> bool {
        use SectionType::*;

        matches!(self, Romx(..) | Vram | Sram | Wramx)
    }

    /// The section type's name.
    pub fn name(&self) -> &'static str {
        use SectionType::*;

        match self {
            Wram0 => "WRAM0",
            Vram => "VRAM",
            Romx(..) => "ROMX",
            Rom0(..) => "ROM0",
            Hram => "HRAM",
            Wramx => "WRAMX",
            Sram => "SRAM",
            Oam => "OAM",
        }
    }
}
impl Display for SectionType {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "{}", self.name())
    }
}

/// A section modifier.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SectionMod {
    Normal,
    Union,
    Fragment,
}
impl SectionMod {
    fn from(byte: u8) -> Result<Self, io::Error> {
        use SectionMod::*;

        Ok(match byte & 0xC0 {
            0x00 => Normal,
            0x80 => Union,
            0x40 => Fragment,
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "Invalid section modifier",
                ))
            }
        })
    }

    /// The modifier's name, except that there is no such name for "regular" sections.
    pub fn name(&self) -> Option<&'static str> {
        use SectionMod::*;

        match self {
            Normal => None,
            Union => Some("UNION"),
            Fragment => Some("FRAGMENT"),
        }
    }
}

/// A ROM section's data.
#[derive(Debug)]
pub struct SectionData {
    data: Vec<u8>,
    patches: Vec<Patch>,
}
impl SectionData {
    fn read_from(mut input: impl Read, size: usize) -> Result<Self, io::Error> {
        let mut data = vec![0; size];
        input.read_exact(&mut data)?;

        let nb_patches = read_u32le(&mut input)?.try_into().unwrap();
        let mut patches = Vec::with_capacity(nb_patches);
        for _ in 0..nb_patches {
            patches.push(Patch::read_from(&mut input)?);
        }

        Ok(Self { data, patches })
    }

    /// The section's data.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// The section's patches.
    pub fn patches(&self) -> &[Patch] {
        &self.patches
    }
}