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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use core::fmt;
use anyhow::anyhow;
use enum_iterator::all;
use hidapi::HidApi;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub mod command;
pub use command::{Command, KeystoreOperation, Response};
pub mod error;
pub mod property;
pub use property::{GetProperties, Properties, Property};
pub mod protocol;
pub mod provision;
use protocol::Protocol;
pub trait UuidSelectable: Sized {
fn try_uuid(&mut self) -> anyhow::Result<Uuid>;
fn list() -> Vec<Self>;
fn having(uuid: Uuid) -> anyhow::Result<Self> {
let mut candidates: Vec<Self> = Self::list()
.into_iter()
.filter_map(|mut entry| {
if let Ok(entry_uuid) = entry.try_uuid() {
if entry_uuid == uuid {
Some(entry)
} else {
None
}
} else {
None
}
})
.collect();
match candidates.len() {
0 => Err(anyhow!("No candidate has UUID {:X}", uuid.simple())),
1 => Ok(candidates.remove(0)),
n => Err(anyhow!(
"Multiple ({}) candidates have UUID {:X}",
n,
uuid.simple()
)),
}
}
}
pub struct Bootloader {
pub protocol: Protocol,
pub vid: u16,
pub pid: u16,
pub uuid: u128,
}
impl fmt::Debug for Bootloader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Bootloader")
.field("vid", &hexstr!(&self.vid.to_be_bytes()))
.field("pid", &hexstr!(&self.pid.to_be_bytes()))
.field("uuid", &hexstr!(&self.uuid.to_be_bytes()))
.finish()
}
}
impl fmt::Display for Bootloader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum Error {
Generic(error::GenericError),
FlashDriver(error::FlashDriverError),
PropertyStore(error::PropertyStoreError),
CrcChecker(error::CrcCheckerError),
SbLoader(error::SbLoaderError),
Unknown(u32),
}
pub type Result<T> = std::result::Result<T, Error>;
impl UuidSelectable for Bootloader {
fn try_uuid(&mut self) -> anyhow::Result<Uuid> {
Ok(self.uuid())
}
fn having(uuid: Uuid) -> anyhow::Result<Self> {
let mut candidates: Vec<Self> = Self::list()
.into_iter()
.filter(|bootloader| bootloader.uuid() == uuid)
.collect();
match candidates.len() {
0 => Err(anyhow!("No usable bootloader has UUID {:X}", uuid.simple())),
1 => Ok(candidates.remove(0)),
n => Err(anyhow!(
"Multiple ({}) bootloaders have UUID {:X}",
n,
uuid.simple()
)),
}
}
fn list() -> Vec<Self> {
let api = HidApi::new().unwrap();
api.device_list()
.filter_map(|device_info| {
let vid = device_info.vendor_id();
let pid = device_info.product_id();
if device_info.manufacturer_string() != Some("NXP SEMICONDUCTOR INC.") {
return None;
}
if device_info.product_string() != Some("USB COMPOSITE DEVICE") {
return None;
}
device_info
.open_device(&api)
.ok()
.map(|device| (device, vid, pid))
})
.filter_map(|(device, vid, pid)| {
let protocol = Protocol::new(device);
GetProperties {
protocol: &protocol,
}
.device_uuid()
.ok()
.map(|uuid| Self {
protocol,
vid,
pid,
uuid,
})
})
.collect()
}
}
impl Bootloader {
fn uuid(&self) -> Uuid {
Uuid::from_u128(self.uuid)
}
pub fn try_new(vid: Option<u16>, pid: Option<u16>) -> anyhow::Result<Self> {
Self::try_find(vid, pid, None)
}
pub fn try_find(
vid: Option<u16>,
pid: Option<u16>,
uuid: Option<Uuid>,
) -> anyhow::Result<Self> {
let mut bootloaders = Self::find(vid, pid, uuid);
if bootloaders.len() > 1 {
Err(anyhow!("Muliple matching bootloaders found"))
} else {
bootloaders
.pop()
.ok_or_else(|| anyhow!("No matching bootloader found"))
}
}
pub fn find(vid: Option<u16>, pid: Option<u16>, uuid: Option<Uuid>) -> Vec<Self> {
Self::list()
.into_iter()
.filter(|bootloader| vid.map_or(true, |vid| vid == bootloader.vid))
.filter(|bootloader| pid.map_or(true, |pid| pid == bootloader.pid))
.filter(|bootloader| uuid.map_or(true, |uuid| uuid.as_u128() == bootloader.uuid))
.collect()
}
pub fn info(&self) {
for property in all::<Property>() {
self.property(property).ok();
}
}
pub fn reboot(&self) {
info!("calling Command::Reset");
self.protocol.call(&Command::Reset).expect("success");
}
pub fn enroll_puf(&self) {
self.protocol
.call(&Command::Keystore(KeystoreOperation::Enroll))
.expect("success");
info!("PUF enrolled");
}
pub fn read_memory(&self, address: usize, length: usize) -> Vec<u8> {
let mut data = Vec::new();
let mut remaining = length;
let mut address = address;
while remaining > 0 {
let length = core::cmp::min(remaining, 512);
data.extend_from_slice(&self.read_memory_at_most_512(address, length));
remaining -= length;
address += length;
}
data
}
pub fn read_memory_at_most_512(&self, address: usize, length: usize) -> Vec<u8> {
let response = self
.protocol
.call(&Command::ReadMemory { address, length })
.expect("success");
if let Response::ReadMemory(data) = response {
data
} else {
todo!();
}
}
pub fn receive_sb_file<'a>(&self, data: &[u8], progress: Option<&'a dyn Fn(usize)>) {
let _response = self
.protocol
.call_progress(
&Command::ReceiveSbFile {
data: data.to_vec(),
},
progress,
)
.expect("success");
}
pub fn erase_flash(&self, address: usize, length: usize) {
let _response = self
.protocol
.call(&Command::EraseFlash { address, length })
.expect("success");
}
pub fn write_memory(&self, address: usize, data: Vec<u8>) {
let _response = self
.protocol
.call(&Command::WriteMemory { address, data })
.expect("success");
}
fn property(&self, property: property::Property) -> Result<Vec<u32>> {
self.protocol.property(property)
}
pub fn properties(&self) -> property::GetProperties<'_> {
GetProperties {
protocol: &self.protocol,
}
}
pub fn all_properties(&self) -> Properties {
self.properties().all()
}
pub fn run_command(
&self,
cmd: Command,
) -> std::result::Result<command::Response, protocol::Error> {
self.protocol.call(&cmd)
}
}
#[cfg(all(feature = "with-device", test))]
fn all_properties() {
let (vid, pid) = (0x1209, 0xb000);
let bootloader = Bootloader::try_new(Some(vid), Some(pid)).unwrap();
insta::assert_debug_snapshot!(bootloader.all_properties());
}