blob: 8cf267c0ac8909fab3450dd3fc49ebaa2acedb3b [file] [log] [blame]
David Brownde7729e2017-01-09 10:41:35 -07001//! A flash simulator
2//!
3//! This module is capable of simulating the type of NOR flash commonly used in microcontrollers.
4//! These generally can be written as individual bytes, but must be erased in larger units.
5
6use std::iter::Enumerate;
7use std::slice;
8use pdump::HexDump;
9
10error_chain! {
11 errors {
12 OutOfBounds(t: String) {
13 description("Offset is out of bounds")
14 display("Offset out of bounds: {}", t)
15 }
16 Write(t: String) {
17 description("Invalid write")
18 display("Invalid write: {}", t)
19 }
20 }
21}
22
23fn ebounds<T: AsRef<str>>(message: T) -> ErrorKind {
24 ErrorKind::OutOfBounds(message.as_ref().to_owned())
25}
26
27fn ewrite<T: AsRef<str>>(message: T) -> ErrorKind {
28 ErrorKind::Write(message.as_ref().to_owned())
29}
30
31/// An emulated flash device. It is represented as a block of bytes, and a list of the sector
32/// mapings.
33#[derive(Clone)]
34pub struct Flash {
35 data: Vec<u8>,
36 sectors: Vec<usize>,
37}
38
39impl Flash {
40 /// Given a sector size map, construct a flash device for that.
41 pub fn new(sectors: Vec<usize>) -> Flash {
42 let total = sectors.iter().sum();
43 Flash {
44 data: vec![0xffu8; total],
45 sectors: sectors,
46 }
47 }
48
49 /// The flash drivers tend to erase beyond the bounds of the given range. Instead, we'll be
50 /// strict, and make sure that the passed arguments are exactly at a sector boundary, otherwise
51 /// return an error.
52 pub fn erase(&mut self, offset: usize, len: usize) -> Result<()> {
53 let (_start, slen) = self.get_sector(offset).ok_or_else(|| ebounds("start"))?;
54 let (end, elen) = self.get_sector(offset + len - 1).ok_or_else(|| ebounds("end"))?;
55
56 if slen != 0 {
57 bail!(ebounds("offset not at start of sector"));
58 }
59 if elen != self.sectors[end] - 1 {
60 bail!(ebounds("end not at start of sector"));
61 }
62
63 for x in &mut self.data[offset .. offset + len] {
64 *x = 0xff;
65 }
66
67 Ok(())
68 }
69
70 /// Writes are fairly unconstrained, but we restrict to only allowing writes of values that
71 /// are entirely written as 0xFF.
72 pub fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()> {
73 if offset + payload.len() > self.data.len() {
74 bail!(ebounds("Write outside of device"));
75 }
76
77 let mut sub = &mut self.data[offset .. offset + payload.len()];
78 if sub.iter().any(|x| *x != 0xFF) {
79 bail!(ewrite("Write to non-FF location"));
80 }
81
82 sub.copy_from_slice(payload);
83 Ok(())
84 }
85
86 /// Read is simple.
87 pub fn read(&self, offset: usize, data: &mut [u8]) -> Result<()> {
88 if offset + data.len() > self.data.len() {
89 bail!(ebounds("Read outside of device"));
90 }
91
92 let sub = &self.data[offset .. offset + data.len()];
93 data.copy_from_slice(sub);
94 Ok(())
95 }
96
97 // Scan the sector map, and return the base and offset within a sector for this given byte.
98 // Returns None if the value is outside of the device.
99 fn get_sector(&self, offset: usize) -> Option<(usize, usize)> {
100 let mut offset = offset;
101 for (sector, &size) in self.sectors.iter().enumerate() {
102 if offset < size {
103 return Some((sector, offset));
104 }
105 offset -= size;
106 }
107 return None;
108 }
109
110 /// An iterator over each sector in the device.
111 pub fn sector_iter(&self) -> SectorIter {
112 SectorIter {
113 iter: self.sectors.iter().enumerate(),
114 base: 0,
115 }
116 }
117
118 pub fn device_size(&self) -> usize {
119 self.data.len()
120 }
121
122 pub fn dump(&self) {
123 self.data.dump();
124 }
125}
126
127/// It is possible to iterate over the sectors in the device, each element returning this.
128#[derive(Debug)]
129pub struct Sector {
130 /// Which sector is this, starting from 0.
131 pub num: usize,
132 /// The offset, in bytes, of the start of this sector.
133 pub base: usize,
134 /// The length, in bytes, of this sector.
135 pub size: usize,
136}
137
138pub struct SectorIter<'a> {
139 iter: Enumerate<slice::Iter<'a, usize>>,
140 base: usize,
141}
142
143impl<'a> Iterator for SectorIter<'a> {
144 type Item = Sector;
145
146 fn next(&mut self) -> Option<Sector> {
147 match self.iter.next() {
148 None => None,
149 Some((num, &size)) => {
150 let base = self.base;
151 self.base += size;
152 Some(Sector {
153 num: num,
154 base: base,
155 size: size,
156 })
157 }
158 }
159 }
160}
161
162#[cfg(test)]
163mod test {
164 use super::{Flash, Error, ErrorKind, Result, Sector};
165
166 #[test]
167 fn test_flash() {
168 // NXP-style, uniform sectors.
169 let mut f1 = Flash::new(vec![4096usize; 256]);
170 test_device(&mut f1);
171
172 // STM style, non-uniform sectors
173 let mut f2 = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
174 128 * 1024, 128 * 1024, 128 * 1024]);
175 test_device(&mut f2);
176 }
177
178 fn test_device(flash: &mut Flash) {
179 let sectors: Vec<Sector> = flash.sector_iter().collect();
180
181 flash.erase(0, sectors[0].size).unwrap();
182 let flash_size = flash.device_size();
183 flash.erase(0, flash_size).unwrap();
184 assert!(flash.erase(0, sectors[0].size - 1).is_bounds());
185
186 // Verify that write and erase do something.
187 flash.write(0, &[0]).unwrap();
188 let mut buf = [0; 4];
189 flash.read(0, &mut buf).unwrap();
190 assert_eq!(buf, [0, 0xff, 0xff, 0xff]);
191
192 flash.erase(0, sectors[0].size).unwrap();
193 flash.read(0, &mut buf).unwrap();
194 assert_eq!(buf, [0xff; 4]);
195
196 // Program the first and last byte of each sector, verify that has been done, and then
197 // erase to verify the erase boundaries.
198 for sector in &sectors {
199 let byte = [(sector.num & 127) as u8];
200 flash.write(sector.base, &byte).unwrap();
201 flash.write(sector.base + sector.size - 1, &byte).unwrap();
202 }
203
204 // Verify the above
205 let mut buf = Vec::new();
206 for sector in &sectors {
207 let byte = (sector.num & 127) as u8;
208 buf.resize(sector.size, 0);
209 flash.read(sector.base, &mut buf).unwrap();
210 assert_eq!(buf.first(), Some(&byte));
211 assert_eq!(buf.last(), Some(&byte));
212 assert!(buf[1..buf.len()-1].iter().all(|&x| x == 0xff));
213 }
214 }
215
216 // Helper checks for the result type.
217 trait EChecker {
218 fn is_bounds(&self) -> bool;
219 }
220
221 impl<T> EChecker for Result<T> {
222
223 fn is_bounds(&self) -> bool {
224 match *self {
225 Err(Error(ErrorKind::OutOfBounds(_), _)) => true,
226 _ => false,
227 }
228 }
229 }
230}