Skip to main content

i8051_disassembler/commands/
platform_addr.rs

1use crate::address::SpaceAddressValue;
2use crate::db::{Db, Error, ErrorKind};
3
4use super::{Apply, Command, Environment, boxed};
5
6#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
7pub struct DisablePlatformAddress {
8    pub address: SpaceAddressValue,
9    pub reason: String,
10}
11
12register!(DisablePlatformAddress(
13    /// Record that a platform address is disabled, along with a reason.
14    ///
15    /// The platform's default addresses are recommended, but not required and
16    /// in some cases the addresses are re-used, re-purposed or otherwise would
17    /// not analyze properly.
18    address: SpaceAddressValue,
19    reason: String,
20));
21
22impl Apply for DisablePlatformAddress {
23    fn apply(
24        self,
25        db: &mut Db,
26        _env: Option<&dyn Environment>,
27    ) -> Result<Vec<Box<dyn Command>>, Error> {
28        let Self { address, reason } = self;
29        if reason.trim().is_empty() {
30            return Err(ErrorKind::InvalidArgument {
31                value: reason,
32                reason: "a reason is required: say why this does not apply here",
33            }
34            .into());
35        }
36        let claimed = db.platform().is_some_and(|p| {
37            p.entry_points()
38                .iter()
39                .any(|e| e.space == address.space && e.offset == address.offset)
40        });
41        if !claimed {
42            return Err(ErrorKind::InvalidArgument {
43                value: address.space.dsl_addr(address.offset),
44                reason: "the platform doesn't list this address, so there is nothing to disable",
45            }
46            .into());
47        }
48        let previous = db
49            .region_mut(address.space)
50            .disable_platform_address(address.offset, reason);
51        Ok(match previous {
52            Some(reason) => vec![boxed(DisablePlatformAddress { address, reason })],
53            None => vec![boxed(RestorePlatformAddress { address })],
54        })
55    }
56}
57
58#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
59pub struct RestorePlatformAddress {
60    pub address: SpaceAddressValue,
61}
62
63register!(RestorePlatformAddress(
64    /// Restore a platform address, undoing `disable_platform_address`.
65    address: SpaceAddressValue,
66));
67
68impl Apply for RestorePlatformAddress {
69    fn apply(
70        self,
71        db: &mut Db,
72        _env: Option<&dyn Environment>,
73    ) -> Result<Vec<Box<dyn Command>>, Error> {
74        let Self { address } = self;
75        let previous = db
76            .region_mut(address.space)
77            .enable_platform_address(address.offset);
78        Ok(match previous {
79            Some(reason) => vec![boxed(DisablePlatformAddress { address, reason })],
80            None => Vec::new(),
81        })
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use crate::commands::MapBytes;
89    use crate::platform::i8051::CODE;
90
91    struct Env;
92    impl crate::commands::Environment for Env {
93        fn load_file_bytes(
94            &self,
95            _f: &str,
96            offset: usize,
97            size: crate::address::AddressValue,
98        ) -> Result<Vec<u8>, std::io::Error> {
99            Ok(vec![0u8; offset + size as usize][offset..].to_vec())
100        }
101    }
102
103    fn mapped() -> Db {
104        let mut db = Db::with_platform(crate::platform::i8051::platform());
105        db.apply(
106            boxed(MapBytes::new((CODE, 0), "img", 0usize, 0x30u32)),
107            Some(&Env),
108        )
109        .unwrap();
110        db
111    }
112
113    fn disabled(db: &Db, offset: u32) -> bool {
114        db.region(CODE)
115            .is_some_and(|r| r.platform_address_disabled(offset))
116    }
117
118    #[test]
119    fn disabling_vector_round_trips() {
120        let mut db = mapped();
121        assert!(!disabled(&db, 0x13));
122
123        let undo = db
124            .apply(
125                boxed(DisablePlatformAddress {
126                    address: (CODE, 0x13u32).into(),
127                    reason: "IE=0x92 never enables EX1".to_string(),
128                }),
129                Some(&Env),
130            )
131            .unwrap();
132        assert!(disabled(&db, 0x13));
133
134        let dsl = crate::store::to_dsl_many(&db.to_commands());
135        assert!(dsl.contains("disable_platform_address"), "{dsl}");
136        assert!(dsl.contains("IE=0x92"), "the reason: {dsl}");
137
138        let mut replayed = Db::new();
139        for command in crate::store::from_dsl_many(&dsl).expect("export parses") {
140            replayed.apply(command, Some(&Env)).expect("export replays");
141        }
142        assert!(disabled(&replayed, 0x13), "reloaded: {dsl}");
143
144        for command in undo {
145            db.apply(command, Some(&Env)).unwrap();
146        }
147        assert!(!disabled(&db, 0x13), "restoring reopens");
148    }
149}