Skip to main content

i8051_disassembler/commands/
bytes.rs

1use crate::address::{AddressValue, SpaceAddressRange, SpaceAddressSet, SpaceAddressValue};
2use crate::db::{Db, Error, ErrorKind, marked_word};
3use crate::region::ByteRange;
4use crate::store::dsl;
5
6use super::{Apply, Command, Environment, boxed};
7
8#[cfg(test)]
9use crate::address::AddressRange;
10
11#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
12pub struct MapBytes {
13    pub address: SpaceAddressValue,
14    pub file: String,
15    pub file_offset: usize,
16    pub size: AddressValue,
17}
18
19register!(MapBytes(
20    /// Map `size` bytes from `file` (at `file_offset`) into the address space
21    /// starting at `address`.
22    address: SpaceAddressValue,
23    file: String,
24    file_offset: usize,
25    size: AddressValue,
26));
27
28impl Apply for MapBytes {
29    fn apply(
30        self,
31        db: &mut Db,
32        env: Option<&dyn Environment>,
33    ) -> Result<Vec<Box<dyn Command>>, Error> {
34        let Self {
35            address,
36            file,
37            file_offset,
38            size,
39        } = self;
40        let SpaceAddressValue { space, offset } = address;
41        let region = db.region_mut(space);
42        let Some(env) = env else {
43            return Err(ErrorKind::NoEnvironment.into());
44        };
45        let bytes = env
46            .load_file_bytes(&file, file_offset, size)
47            .map_err(Error::from)?;
48        let size = bytes.len() as AddressValue;
49        let before = region.snapshot_byte_ranges(offset, size);
50        region.map_bytes(&file, file_offset, offset, &bytes);
51        let mut addresses = SpaceAddressSet::new(space);
52        addresses.insert(offset..offset + size);
53        Ok(undo_byte_ranges(addresses, before))
54    }
55}
56
57#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
58pub struct UnmapBytes {
59    pub addresses: SpaceAddressSet,
60}
61
62register!(UnmapBytes(
63    /// Unmap the bytes covered by `addresses`, along with whatever classified
64    /// them. The inverse of `map_bytes`.
65    addresses: SpaceAddressSet,
66));
67
68impl Apply for UnmapBytes {
69    fn apply(
70        self,
71        db: &mut Db,
72        _env: Option<&dyn Environment>,
73    ) -> Result<Vec<Box<dyn Command>>, Error> {
74        let Self { addresses } = self;
75        let space = addresses.space;
76        let region = db.region_mut(space);
77
78        // Refuse to cut a classification
79        for range in addresses.ranges() {
80            for (start, equivalent) in
81                region.snapshot_equivalents(range.start, range.end - range.start)
82            {
83                if start < range.start || equivalent.end > range.end {
84                    let end = equivalent.end;
85                    let kind = ErrorKind::PartialEquivalent {
86                        range: space.dsl_range(start, end),
87                        marked: marked_word(equivalent.equivalent.kind()).to_string(),
88                    };
89                    return Err(Error::from(kind).suggest(vec![dsl!(clear_equivalents(
90                        addresses = {space.dsl_set(start, end)}
91                    ) # "then unmap again")]));
92                }
93            }
94        }
95
96        let mut before = Vec::new();
97        let mut equivalents = Vec::new();
98        for range in addresses.ranges() {
99            let offset = range.start;
100            let size = range.end - range.start;
101            for (start, equivalent) in region.snapshot_equivalents(offset, size) {
102                equivalents.push(super::equivalent::restore_equivalent(
103                    space, start, equivalent,
104                ));
105            }
106            region.clear_equivalents(offset, size);
107            before.extend(region.snapshot_byte_ranges(offset, size));
108            region.unmap_bytes(offset, size);
109        }
110
111        // Bytes first, so the classifications land on mapped memory.
112        let mut undo = undo_byte_ranges(addresses, before);
113        undo.extend(equivalents);
114        Ok(undo)
115    }
116}
117
118#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
119pub struct SetConstantBytes {
120    pub range: SpaceAddressRange,
121    pub value: u8,
122}
123
124register!(SetConstantBytes(
125    /// Fill the bytes covered by `range` with the constant `value`.
126    range: SpaceAddressRange,
127    value: u8,
128));
129
130impl Apply for SetConstantBytes {
131    fn apply(
132        self,
133        db: &mut Db,
134        _env: Option<&dyn Environment>,
135    ) -> Result<Vec<Box<dyn Command>>, Error> {
136        let Self { range, value } = self;
137        let SpaceAddressRange {
138            space,
139            range: address_range,
140        } = range;
141        let offset = address_range.start;
142        let size = address_range.end - address_range.start;
143        let region = db.region_mut(space);
144        let before = region.snapshot_byte_ranges(offset, size);
145        region.set_constant(offset, size, value);
146        let mut addresses = SpaceAddressSet::new(space);
147        addresses.insert(offset..offset + size);
148        Ok(undo_byte_ranges(addresses, before))
149    }
150}
151
152/// Build the undo for an operation that overwrote the byte ranges in
153/// `addresses`: first re-clear that whole set, then restore each prior range.
154fn undo_byte_ranges(
155    addresses: SpaceAddressSet,
156    ranges: Vec<(AddressValue, ByteRange)>,
157) -> Vec<Box<dyn Command>> {
158    let space = addresses.space;
159    let mut undo = vec![boxed(UnmapBytes::new(addresses))];
160    for (start, range) in ranges {
161        match range {
162            ByteRange::Mapped(file, file_offset, data) => {
163                undo.push(boxed(MapBytes::new(
164                    (space, start),
165                    file,
166                    file_offset,
167                    data.len() as AddressValue,
168                )));
169            }
170            ByteRange::Constant(count, value) => {
171                undo.push(boxed(SetConstantBytes::new(
172                    (space, start..start + count as AddressValue),
173                    value,
174                )));
175            }
176        }
177    }
178    undo
179}
180
181// Address range + a `u8` field, both rendered in hex.
182serialize_test!(
183    constant_bytes_range_and_byte,
184    "set_constant_bytes(range=CODE:0x10..0x20, value=0xFF)",
185    SetConstantBytes {
186        range: (crate::platform::i8051::CODE, AddressRange::new(0x10, 0x20)).into(),
187        value: 0xFF,
188    }
189);
190
191#[cfg(test)]
192mod unmap_bytes_tests {
193    use super::*;
194    use crate::commands::{MarkUnknown, boxed};
195    use crate::db::Db;
196    use crate::platform::i8051::CODE;
197
198    struct Env;
199    impl crate::commands::Environment for Env {
200        fn load_file_bytes(
201            &self,
202            _f: &str,
203            offset: usize,
204            size: AddressValue,
205        ) -> Result<Vec<u8>, std::io::Error> {
206            Ok(vec![0x00; offset + size as usize][offset..].to_vec())
207        }
208    }
209
210    fn mapped() -> Db {
211        let mut db = Db::with_platform(crate::platform::i8051::platform());
212        db.apply(
213            boxed(MapBytes::new((CODE, 0), "img", 0usize, 0x10u32)),
214            Some(&Env),
215        )
216        .unwrap();
217        db
218    }
219
220    #[test]
221    fn unmap_takes_classification() {
222        let mut db = mapped();
223        db.apply(boxed(MarkUnknown::new((CODE, 0x8u32..0x9u32))), Some(&Env))
224            .unwrap();
225
226        let undo = db
227            .apply(boxed(UnmapBytes::new((CODE, 0x8u32..0x9u32))), Some(&Env))
228            .unwrap();
229
230        let dsl = crate::store::to_dsl_many(&db.to_commands());
231        let mut replayed = Db::new();
232        for command in crate::store::from_dsl_many(&dsl).expect("export parses") {
233            replayed
234                .apply(command, Some(&Env))
235                .expect("every exported command must apply to a fresh database");
236        }
237
238        for command in undo {
239            db.apply(command, Some(&Env)).unwrap();
240        }
241        let restored = crate::store::to_dsl_many(&db.to_commands());
242        assert!(restored.contains("mark_unknown"), "{restored}");
243    }
244
245    #[test]
246    fn partial_unmap_refused() {
247        let mut db = mapped();
248        db.apply(boxed(MarkUnknown::new((CODE, 0x4u32..0xCu32))), Some(&Env))
249            .unwrap();
250        let before = crate::store::to_dsl_many(&db.to_commands());
251
252        let err = db
253            .apply(boxed(UnmapBytes::new((CODE, 0x8u32..0x9u32))), Some(&Env))
254            .expect_err("a partial cut must not be obeyed");
255        assert!(
256            matches!(err.what, ErrorKind::PartialEquivalent { .. }),
257            "{err:?}"
258        );
259
260        assert_eq!(crate::store::to_dsl_many(&db.to_commands()), before);
261    }
262}