blob: 125db6c2069ce36d5c302d0dad60ed31d0e5c048 [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
David Brown163ab232017-01-23 15:48:35 -07006use std::fs::File;
7use std::io::Write;
David Brownde7729e2017-01-09 10:41:35 -07008use std::iter::Enumerate;
David Brown163ab232017-01-23 15:48:35 -07009use std::path::Path;
David Brownde7729e2017-01-09 10:41:35 -070010use std::slice;
11use pdump::HexDump;
12
13error_chain! {
14 errors {
15 OutOfBounds(t: String) {
16 description("Offset is out of bounds")
17 display("Offset out of bounds: {}", t)
18 }
19 Write(t: String) {
20 description("Invalid write")
21 display("Invalid write: {}", t)
22 }
23 }
24}
25
26fn ebounds<T: AsRef<str>>(message: T) -> ErrorKind {
27 ErrorKind::OutOfBounds(message.as_ref().to_owned())
28}
29
30fn ewrite<T: AsRef<str>>(message: T) -> ErrorKind {
31 ErrorKind::Write(message.as_ref().to_owned())
32}
33
34/// An emulated flash device. It is represented as a block of bytes, and a list of the sector
35/// mapings.
36#[derive(Clone)]
37pub struct Flash {
38 data: Vec<u8>,
Marti Bolivar51d36dd2017-05-17 17:39:46 -040039 write_safe: Vec<bool>,
David Brownde7729e2017-01-09 10:41:35 -070040 sectors: Vec<usize>,
David Brown562a7a02017-01-23 11:19:03 -070041 // Alignment required for writes.
42 align: usize,
David Brownde7729e2017-01-09 10:41:35 -070043}
44
45impl Flash {
46 /// Given a sector size map, construct a flash device for that.
David Brown562a7a02017-01-23 11:19:03 -070047 pub fn new(sectors: Vec<usize>, align: usize) -> Flash {
48 // Verify that the alignment is a positive power of two.
49 assert!(align > 0);
50 assert!(align & (align - 1) == 0);
51
David Brownde7729e2017-01-09 10:41:35 -070052 let total = sectors.iter().sum();
53 Flash {
54 data: vec![0xffu8; total],
Marti Bolivar51d36dd2017-05-17 17:39:46 -040055 write_safe: vec![true; total],
David Brownde7729e2017-01-09 10:41:35 -070056 sectors: sectors,
David Brown562a7a02017-01-23 11:19:03 -070057 align: align,
David Brownde7729e2017-01-09 10:41:35 -070058 }
59 }
60
61 /// The flash drivers tend to erase beyond the bounds of the given range. Instead, we'll be
62 /// strict, and make sure that the passed arguments are exactly at a sector boundary, otherwise
63 /// return an error.
64 pub fn erase(&mut self, offset: usize, len: usize) -> Result<()> {
65 let (_start, slen) = self.get_sector(offset).ok_or_else(|| ebounds("start"))?;
66 let (end, elen) = self.get_sector(offset + len - 1).ok_or_else(|| ebounds("end"))?;
67
68 if slen != 0 {
69 bail!(ebounds("offset not at start of sector"));
70 }
71 if elen != self.sectors[end] - 1 {
72 bail!(ebounds("end not at start of sector"));
73 }
74
75 for x in &mut self.data[offset .. offset + len] {
76 *x = 0xff;
77 }
78
Marti Bolivar51d36dd2017-05-17 17:39:46 -040079 for x in &mut self.write_safe[offset .. offset + len] {
80 *x = true;
81 }
82
David Brownde7729e2017-01-09 10:41:35 -070083 Ok(())
84 }
85
Marti Bolivar51d36dd2017-05-17 17:39:46 -040086 /// We restrict to only allowing writes of values that are:
87 ///
88 /// 1. being written to for the first time
89 /// 2. being written to after being erased
90 ///
91 /// This emulates a flash device which starts out erased, with the
92 /// added restriction that repeated writes to the same location
93 /// are disallowed, even if they would be safe to do.
David Brownde7729e2017-01-09 10:41:35 -070094 pub fn write(&mut self, offset: usize, payload: &[u8]) -> Result<()> {
95 if offset + payload.len() > self.data.len() {
David Brownf253fa82017-01-23 15:43:47 -070096 panic!("Write outside of device");
David Brownde7729e2017-01-09 10:41:35 -070097 }
98
David Brown562a7a02017-01-23 11:19:03 -070099 // Verify the alignment (which must be a power of two).
100 if offset & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700101 panic!("Misaligned write address");
David Brown562a7a02017-01-23 11:19:03 -0700102 }
103
104 if payload.len() & (self.align - 1) != 0 {
David Brownf253fa82017-01-23 15:43:47 -0700105 panic!("Write length not multiple of alignment");
David Brown562a7a02017-01-23 11:19:03 -0700106 }
107
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400108 for (i, x) in &mut self.write_safe[offset .. offset + payload.len()].iter_mut().enumerate() {
109 if !(*x) {
110 bail!(ewrite(format!("Write to unerased location at 0x{:x}", i)));
Fabio Utzig19b2c1a2017-04-20 07:32:44 -0300111 }
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400112 *x = false;
David Brownde7729e2017-01-09 10:41:35 -0700113 }
114
Marti Bolivar51d36dd2017-05-17 17:39:46 -0400115 let mut sub = &mut self.data[offset .. offset + payload.len()];
David Brownde7729e2017-01-09 10:41:35 -0700116 sub.copy_from_slice(payload);
117 Ok(())
118 }
119
120 /// Read is simple.
121 pub fn read(&self, offset: usize, data: &mut [u8]) -> Result<()> {
122 if offset + data.len() > self.data.len() {
123 bail!(ebounds("Read outside of device"));
124 }
125
126 let sub = &self.data[offset .. offset + data.len()];
127 data.copy_from_slice(sub);
128 Ok(())
129 }
130
131 // Scan the sector map, and return the base and offset within a sector for this given byte.
132 // Returns None if the value is outside of the device.
133 fn get_sector(&self, offset: usize) -> Option<(usize, usize)> {
134 let mut offset = offset;
135 for (sector, &size) in self.sectors.iter().enumerate() {
136 if offset < size {
137 return Some((sector, offset));
138 }
139 offset -= size;
140 }
141 return None;
142 }
143
144 /// An iterator over each sector in the device.
145 pub fn sector_iter(&self) -> SectorIter {
146 SectorIter {
147 iter: self.sectors.iter().enumerate(),
148 base: 0,
149 }
150 }
151
152 pub fn device_size(&self) -> usize {
153 self.data.len()
154 }
155
156 pub fn dump(&self) {
157 self.data.dump();
158 }
David Brown163ab232017-01-23 15:48:35 -0700159
160 /// Dump this image to the given file.
161 pub fn write_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
162 let mut fd = File::create(path).chain_err(|| "Unable to write image file")?;
163 fd.write_all(&self.data).chain_err(|| "Unable to write to image file")?;
164 Ok(())
165 }
David Brownde7729e2017-01-09 10:41:35 -0700166}
167
168/// It is possible to iterate over the sectors in the device, each element returning this.
169#[derive(Debug)]
170pub struct Sector {
171 /// Which sector is this, starting from 0.
172 pub num: usize,
173 /// The offset, in bytes, of the start of this sector.
174 pub base: usize,
175 /// The length, in bytes, of this sector.
176 pub size: usize,
177}
178
179pub struct SectorIter<'a> {
180 iter: Enumerate<slice::Iter<'a, usize>>,
181 base: usize,
182}
183
184impl<'a> Iterator for SectorIter<'a> {
185 type Item = Sector;
186
187 fn next(&mut self) -> Option<Sector> {
188 match self.iter.next() {
189 None => None,
190 Some((num, &size)) => {
191 let base = self.base;
192 self.base += size;
193 Some(Sector {
194 num: num,
195 base: base,
196 size: size,
197 })
198 }
199 }
200 }
201}
202
203#[cfg(test)]
204mod test {
205 use super::{Flash, Error, ErrorKind, Result, Sector};
206
207 #[test]
208 fn test_flash() {
209 // NXP-style, uniform sectors.
210 let mut f1 = Flash::new(vec![4096usize; 256]);
211 test_device(&mut f1);
212
213 // STM style, non-uniform sectors
214 let mut f2 = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
215 128 * 1024, 128 * 1024, 128 * 1024]);
216 test_device(&mut f2);
217 }
218
219 fn test_device(flash: &mut Flash) {
220 let sectors: Vec<Sector> = flash.sector_iter().collect();
221
222 flash.erase(0, sectors[0].size).unwrap();
223 let flash_size = flash.device_size();
224 flash.erase(0, flash_size).unwrap();
225 assert!(flash.erase(0, sectors[0].size - 1).is_bounds());
226
227 // Verify that write and erase do something.
228 flash.write(0, &[0]).unwrap();
229 let mut buf = [0; 4];
230 flash.read(0, &mut buf).unwrap();
231 assert_eq!(buf, [0, 0xff, 0xff, 0xff]);
232
233 flash.erase(0, sectors[0].size).unwrap();
234 flash.read(0, &mut buf).unwrap();
235 assert_eq!(buf, [0xff; 4]);
236
237 // Program the first and last byte of each sector, verify that has been done, and then
238 // erase to verify the erase boundaries.
239 for sector in &sectors {
240 let byte = [(sector.num & 127) as u8];
241 flash.write(sector.base, &byte).unwrap();
242 flash.write(sector.base + sector.size - 1, &byte).unwrap();
243 }
244
245 // Verify the above
246 let mut buf = Vec::new();
247 for sector in &sectors {
248 let byte = (sector.num & 127) as u8;
249 buf.resize(sector.size, 0);
250 flash.read(sector.base, &mut buf).unwrap();
251 assert_eq!(buf.first(), Some(&byte));
252 assert_eq!(buf.last(), Some(&byte));
253 assert!(buf[1..buf.len()-1].iter().all(|&x| x == 0xff));
254 }
255 }
256
257 // Helper checks for the result type.
258 trait EChecker {
259 fn is_bounds(&self) -> bool;
260 }
261
262 impl<T> EChecker for Result<T> {
263
264 fn is_bounds(&self) -> bool {
265 match *self {
266 Err(Error(ErrorKind::OutOfBounds(_), _)) => true,
267 _ => false,
268 }
269 }
270 }
271}