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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
// Copyright 2025 NXP
//
// SPDX-License-Identifier: BSD-3-Clause
#![allow(
clippy::doc_markdown,
clippy::missing_errors_doc,
reason = "Docs here are not used by rustdoc, they are used by clap for CLI help"
)]
use std::{
fs::File,
io::{Read, Write},
};
mod image_parser;
mod parsers;
use std::path::Path;
use clap::{Arg, ArgGroup, Parser, Subcommand};
use image_parser::ImageParser;
use log::{LevelFilter, debug, warn};
use mboot::{
CommunicationError, GetPropertyResponse, KeyProvisioningResponse, McuBoot, ReadMemoryResponse,
protocols::{Protocol, ProtocolOpen, i2c::I2CProtocol, uart::UARTProtocol, usb::USBProtocol},
tags::{
command::{KeyProvOperation, TrustProvOperation},
property::PropertyTagDiscriminants,
status::StatusCode,
},
};
use pretty_hex::{HexConfig, PrettyHex};
fn main() -> anyhow::Result<()> {
let args = std::env::args();
// FIXME this probably isn't the best solution to ignore "--", but it's the best I've come up with to stay compatible with the python version
let args = Args::parse_from(args.filter(|arg| arg != "--"));
env_logger::builder()
.filter_level(match args.verbose {
0 => LevelFilter::Warn,
1 => LevelFilter::Info,
2 => LevelFilter::Debug,
_ => LevelFilter::Trace,
})
.format_timestamp_millis()
.parse_default_env()
.init();
// clap ensures, that at least one of the device is Some
if args.device.port.is_some() {
let mut blhost = Blhost::new_from_uart(args)?;
run_blhost(&mut blhost)?;
} else if args.device.i2c.is_some() {
let mut blhost = Blhost::new_from_i2c(args)?;
run_blhost(&mut blhost)?;
} else if args.device.usb.is_some() {
let mut blhost = Blhost::new_from_usb(args)?;
run_blhost(&mut blhost)?;
}
Ok(())
}
fn run_blhost<T>(blhost: &mut Blhost<T>) -> anyhow::Result<()>
where
T: Protocol,
{
blhost.execute()?;
Ok(())
}
// TODO the original blhost can just *recover* the board when the program crashes and doesn't send ACK? would be nice to have that here too
#[derive(clap::Args, Debug)]
#[group(required = true, multiple = false)]
struct Device {
/// I2C device identifier in format /dev/i2c-X[:0xYY] where X is the bus number
/// and YY is the optional slave address [default: 0x10]
#[arg(long)]
i2c: Option<String>,
/// UART port identifier
///
/// Baudrate can be optionally specified after a colon, e.g. "COM1,38400".
/// Default baudrate is 57600.
#[arg(long, short)]
port: Option<String>,
/// USB-HID device identifier in format "vid,pid" (e.g., "0x1FC9,0x0135")
#[arg(long, short)]
usb: Option<String>,
}
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Args {
#[command(flatten)]
device: Device,
/// Serial read timeout in milliseconds
#[arg(short, long, default_value_t = 5000)]
timeout: u64,
/// Polling interval for reading in milliseconds
#[arg(long, default_value_t = 1)]
polling_interval: u64,
/// Surpress status response and response words
#[arg(short, long)]
silent: bool,
/// Verbosity level, use more for more verbosity
///
/// -v means info, -vv means debug and -vvv and more is trace level. If RUST_LOG environment
/// variable is set, it overrides this option. For more documentation about it, refer to
/// env_logger crate.
#[arg(short, long, action = clap::ArgAction::Count, default_value_t = 0)]
verbose: u8,
/// Command to send to device
#[command(subcommand)]
command: Commands,
#[arg(long, hide = true)]
secret: bool,
}
// this can't be CommandTag directly, some commands (like ReadMemory) provide additional options
#[derive(Subcommand, Debug, Clone)]
pub enum Commands {
/// Queries various bootloader properties and settings.
GetProperty {
/// Number or name representing the requested property
///
/// Available properties:
/// 1 or 'current-version' Bootloader version
/// 2 or 'available-peripherals' Available peripherals
/// 3 or 'flash-start-address' Start of program flash, <index> is required
/// 4 or 'flash-size' Size of program flash, <index> is required
/// 5 or 'flash-sector-size' Size of flash sector, <index> is required
/// 6 or 'flash-block-count' Blocks in flash array, <index> is required
/// 7 or 'available-commands' Available commands
/// 8 or 'check-status' Check Status, <status id> is required
/// 9 or 'reserved'
/// 10 or 'verify-writes' Verify Writes flag
/// 11 or 'max-packet-size' Max supported packet size
/// 12 or 'reserved-regions' Reserved regions
/// 13 or 'reserved'
/// 14 or 'ram-start-address' Start of RAM, <index> is required
/// 15 or 'ram-size-in-bytes' Size of RAM, <index> is required
/// 16 or 'system-device-id' System device identification
/// 17 or 'security-state' Flash security state
/// 18 or 'unique-device-id' Unique device identification
/// 19 or 'flash-fac-support' FAC support flag
/// 20 or 'flash-access-segment-size' FAC segment size
/// 21 or 'flash-access-segment-count' FAC segment count
/// 22 or 'flash-read-margin' Read margin level of program flash
/// 23 or 'qspi/otfad-init-status' QuadSpi initialization status
/// 24 or 'target-version' Target version
/// 25 or 'external-memory-attributes' External memory attributes, <memoryId> is required
/// 26 or 'reliable-update-status' Reliable update status
/// 27 or 'flash-page-size' Flash page size, <index> is required
/// 28 or 'irq-notifier-pin' Interrupt notifier pin
/// 29 or 'pfr-keystore_update-opt' PFR key store update option
/// 30 or 'byte-write-timeout-ms' Byte write timeout in ms
/// 31 or 'fuse-locked-status' Fuse Locked Status
///
/// for kw45xx/k32w1xx devices:
/// 10 or 'verify-erases' Verify Erases flag
/// 20 or 'boot status' Value of Boot Status Register
/// 21 or 'loadable-fw-version' LoadableFWVersion
/// 22 or 'fuse-program-voltage' Fuse Program Voltage
///
/// for mcxa1xx devices:
/// 17 or 'life-cycle' Life Cycle
///
/// Note: Not all the properties are available for all devices.
// a value parser from clap could be used here; however, it can't convert from repr
#[arg(value_parser=PropertyTagDiscriminants::parse_property, verbatim_doc_comment)]
property_tag: PropertyTagDiscriminants,
/// ID of the memory
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
memory_index: u32,
},
/// Reset the device.
///
/// Response packet is sent before the device resets.
Reset,
/// Jumps to code at the provided address.
///
/// The system is returned to a reset state before the jump.
Execute {
/// Jump address.
#[arg(value_parser=parsers::parse_number::<u32>)]
start_address: u32,
/// Function argument pointer passed to R0.
#[arg(value_parser=parsers::parse_number::<u32>)]
argument: u32,
/// Stack pointer. If set to zero, the code being called should
/// set the stack pointer before using the stack.
#[arg(value_parser=parsers::parse_number::<u32>)]
stackpointer: u32,
},
/// Invokes code at an address, passing an argument to it.
///
Call {
/// Jump address.
#[arg(value_parser=parsers::parse_number::<u32>)]
start_address: u32,
/// Function argument pointer passed to R0.
#[arg(value_parser=parsers::parse_number::<u32>)]
argument: u32,
},
/// Perform an erase of the entire flash memory.
///
/// Note: Protected regions are excluded.
FlashEraseAll {
/// ID of the memory to erase
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
memory_id: u32,
},
/// Fills the memory with a pattern.
FillMemory {
/// Starting address
#[arg(value_parser=parsers::parse_number::<u32>)]
start_address: u32,
/// Number of bytes to fill
#[arg(value_parser=parsers::parse_number::<u32>)]
byte_count: u32,
/// Pattern to fill
#[arg(value_parser=parsers::parse_number::<u32>)]
pattern: u32,
},
/// Reads the memory and writes it to a file or stdout.
ReadMemory {
/// Starting address
#[arg(value_parser=parsers::parse_number::<u32>)]
start_address: u32,
/// Number of bytes to read
#[arg(value_parser=parsers::parse_number::<u32>)]
byte_count: u32,
/// Store read bytes into <FILE>
///
/// If you need to specify [MEMORY_ID], use '-' instead of filename to print to stdout.
file: Option<String>,
/// ID of the memory to read from
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
memory_id: u32,
/// Use hexdump format
#[arg(long, short, default_value_t = false)]
use_hexdump: bool,
},
/// Changes properties and options in the bootloader.
///
/// Accepts the same <PROPERTY_TAG> used with the get-property sub-command.
SetProperty {
/// Number or name representing the requested property
///
/// Available properties to set:
/// 10 or 'verify-writes' Verify Writes flag
/// 22 or 'flash-read-margin' Read margin level of program flash
/// 28 or 'irq-notify-pin' Interrupt notifier pin
/// 29 or 'pfr-keystore_update-opt' PFR key store update option
/// 30 or 'byte-write-timeout-ms' Byte write timeout in ms
///
/// for kw45xx/k32w1xx devices:
/// 10 or 'verify-erases' Verify Erases flag
/// 22 or 'fuse-program-voltage' Fuse Program Voltage
///
/// Note: Not all properties can be set on all devices.
#[arg(value_parser=PropertyTagDiscriminants::parse_property, verbatim_doc_comment)]
property_tag: PropertyTagDiscriminants,
/// Value to set <PROPERTY_TAG> to
#[arg(value_parser=parsers::parse_number::<u32>)]
value: u32,
},
/// Sets a config at internal memory to memory with ID.
///
/// The specified configuration block must have been previously written to memory using the write-memory command.
ConfigureMemory {
/// ID of the memory
#[arg(value_parser=parsers::parse_number::<u32>)]
memory_id: u32,
/// Starting address
#[arg(value_parser=parsers::parse_number::<u32>)]
address: u32,
},
/// Erase Complete Flash and Unlock.
FlashEraseAllUnsecure,
/// Erases one or more sectors of the flash memory.
///
/// The start <ADDRESS> and <BYTE_COUNT> must be a multiple of the word size.
/// The entire sector(s) containing the start and end address is erased.
FlashEraseRegion {
/// Starting address
#[arg(value_parser=parsers::parse_number::<u32>)]
start_address: u32,
/// Number of bytes to erase
#[arg(value_parser=parsers::parse_number::<u32>)]
byte_count: u32,
/// ID of the memory to erase
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
memory_id: u32,
},
/// Write memory from a file or CLI.
///
/// Only one of <FILE> (with <LIMIT>) or <BYTES> must be specified.
#[command(
override_usage = concat!(color_print::cstr!("<bold>rblhost write-memory"), " <START_ADDRESS> FILE[,LIMIT] | {{HEX_DATA}} [MEMORY_ID]"),
args=[
Arg::new("FILE").help("write the content of this file"),
Arg::new("LIMIT").help("If specified, load only first [LIMIT] bytes from FILE"),
Arg::new("HEX_DATA").help("A string of hex values: {{112233}}, {{11 22 33}}"),
]
)]
WriteMemory {
/// Starting address
#[arg(value_parser=parsers::parse_number::<u32>, display_order=0)]
start_address: u32,
#[arg(value_parser=parsers::parse_hex_values, hide = true)]
bytes: Box<[u8]>,
/// ID of the memory to write
#[arg(default_value_t = 0)]
memory_id: u32,
},
/// Program fuse.
///
/// Only one of <FILE> (with optional <BYTE_COUNT>) or <HEX_DATA> must be specified.
#[command(
override_usage = concat!(
color_print::cstr!("<bold>rblhost fuse-program"),
" <START_ADDRESS> FILE[,BYTE_COUNT] | {{HEX_DATA}} [MEMORY_ID]"
),
group = ArgGroup::new("file_input").args(&["file", "byte_count"]),
group = ArgGroup::new("hex_input").args(&["hex_data"]),
group = ArgGroup::new("input")
.args(&["file", "hex_data"])
.required(true)
.multiple(false)
)]
FuseProgram {
/// Start address.
#[arg(value_parser = parsers::parse_number::<u32>, display_order = 0)]
start_address: u32,
/// Write the content of this file.
file: Option<String>,
/// If specified, load only first BYTE_COUNT number of bytes.
#[arg(requires = "file")]
byte_count: Option<u32>,
/// A string of hex values: {{112233}}, {{11 22 33}}
#[arg(value_parser = parsers::parse_hex_values)]
hex_data: Option<Box<[u8]>>,
/// ID of memory to read from (default: 0)
#[arg(default_value_t = 0)]
memory_id: u32,
},
/// Reads the fuse and writes it to the file or stdout.
FuseRead {
/// Start address.
#[arg(value_parser=parsers::parse_number::<u32>)]
start_address: u32,
/// Number of bytes to read.
#[arg(value_parser=parsers::parse_number::<u32>)]
byte_count: u32,
/// Store result into this file, if not specified use stdout.
file: Option<String>,
/// ID of memory to read from (default: 0)
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t=0)]
memory_id: u32,
/// Use hexdump format
#[arg(long, short, default_value_t = false)]
use_hexdump: bool,
},
/// Receives a file in a Secure Binary (SB) format.
ReceiveSbFile {
#[arg(value_parser=|s: &str| parsers::parse_file(s, None))]
bytes: Box<[u8]>,
},
/// Read from MCU flash program once region (eFuse/OTP)
FlashReadOnce {
/// Start index of the eFuse/OTP region
#[arg(value_parser=parsers::parse_number::<u32>)]
index: u32,
/// Number of bytes to read (default: 4)
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t=4)]
count: u32,
},
/// Write into MCU program once region (eFuse/OTP)
FlashProgramOnce {
/// Start index of the eFuse/OTP region
#[arg(value_parser=parsers::parse_number::<u32>)]
index: u32,
/// Value to write (32-bit)
#[arg(value_parser=parsers::parse_number::<u32>)]
data: u32,
/// Number of bytes to write (default: 4)
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t=4)]
count: u32,
/// Verify that data were written correctly
#[arg(long, default_value_t = false)]
verify: bool,
},
/// Group of subcommands related to trust provisioning
#[command(subcommand)]
TrustProvisioning(TrustProvOperation),
/// Group of subcommands related to key provisioning
#[command(subcommand)]
KeyProvisioning(KeyProvOperation),
/// Sends a boot image file to the device.
///
/// Only binary files are supported. The <FILE> must be a bootable
/// image which contains the boot image header supported by the MCU
/// bootloader.
LoadImage {
/// Boot file to load
file: String,
},
/// Write a formatted image file to flash memory with optional erasing.
///
/// Supports S-record format files. The command parses the image file to extract
/// memory segments and writes them using flash-erase-region and write-memory calls.
FlashImage {
/// Path to image file (S-record format supported)
file: String,
/// Erase option: 'erase' to erase flash before writing, 'none' to skip erasing
#[arg(default_value = "none")]
erase: String,
/// ID of memory to write to (default: 0)
#[arg(value_parser=parsers::parse_number::<u32>, default_value_t = 0)]
memory_id: u32,
},
}
pub struct Blhost<T>
where
T: Protocol,
{
args: Args,
boot: McuBoot<T>,
}
const DEFAULT_BAUDRATE: u32 = 57600;
impl Blhost<UARTProtocol> {
fn new_from_uart(args: Args) -> Result<Self, CommunicationError> {
let port_spec = args
.device
.port
.as_ref()
.expect("open_uart called without UART argument");
// Parse port and optional baudrate
let mut parts = port_spec.split(',');
let port_name = parts.next().unwrap();
let baudrate = parts
.next()
.map_or(DEFAULT_BAUDRATE, |v| v.parse().unwrap_or(DEFAULT_BAUDRATE));
// Use UART protocol with specified baudrate and timeout
let boot = McuBoot::new(UARTProtocol::open_with_options(
port_name,
baudrate,
std::time::Duration::from_millis(args.timeout),
std::time::Duration::from_millis(args.polling_interval),
)?);
Ok(Blhost { args, boot })
}
}
impl Blhost<I2CProtocol> {
fn new_from_i2c(args: Args) -> Result<Self, CommunicationError> {
let i2c_device = args
.device
.i2c
.as_ref()
.expect("new_from_i2c called without I2C argument");
let boot = McuBoot::new(I2CProtocol::open(i2c_device)?);
Ok(Blhost { args, boot })
}
}
impl Blhost<USBProtocol> {
fn new_from_usb(args: Args) -> Result<Self, CommunicationError> {
let usb_device = args
.device
.usb
.as_ref()
.expect("new_from_usb called without USB argument");
let boot = McuBoot::new(USBProtocol::open_with_options(
usb_device,
0, // Baudrate not used for USB
std::time::Duration::from_millis(args.timeout),
std::time::Duration::from_millis(args.polling_interval),
)?);
Ok(Blhost { args, boot })
}
}
impl<T> Blhost<T>
where
T: Protocol,
{
pub fn new(args: Args, device: T) -> Blhost<T> {
Blhost {
args,
boot: McuBoot::new(device),
}
}
#[allow(clippy::too_many_lines, reason = "match statement here will always be long")]
pub fn execute(&mut self) -> Result<(), CommunicationError> {
self.boot.progress_bar = !self.args.silent;
match self.args.command {
Commands::GetProperty {
property_tag,
memory_index,
} => {
let response = &self.boot.get_property(property_tag, memory_index)?;
self.display_property(response);
}
Commands::Reset => {
let status = self.boot.reset()?;
self.display_status(status);
}
Commands::Execute {
start_address,
argument,
stackpointer,
} => {
let status = self.boot.execute(start_address, argument, stackpointer)?;
self.display_status(status);
}
Commands::Call {
start_address,
argument,
} => {
let status = self.boot.call(start_address, argument)?;
self.display_status(status);
}
Commands::FlashEraseAll { memory_id } => {
let status = self.boot.flash_erase_all(memory_id)?;
self.display_status(status);
}
Commands::FillMemory {
start_address,
byte_count,
pattern,
} => {
let status = self.boot.fill_memory(start_address, byte_count, pattern)?;
self.display_status(status);
}
Commands::ReadMemory {
start_address,
byte_count,
ref file,
memory_id,
use_hexdump,
} => match file.as_deref() {
None | Some("-") => {
let response = self.boot.read_memory(start_address, byte_count, memory_id)?;
self.display_memory_bytes(&response, byte_count, use_hexdump);
}
Some(file_name) => {
let response = self.boot.read_memory(start_address, byte_count, memory_id)?;
let mut file = File::create(file_name).map_err(CommunicationError::FileError)?;
file.write_all(&response.bytes)?;
self.display_memory(&response, byte_count);
}
},
Commands::SetProperty { property_tag, value } => {
let status = self.boot.set_property(property_tag, value)?;
self.display_status(status);
}
Commands::ConfigureMemory { memory_id, address } => {
let status = self.boot.configure_memory(memory_id, address)?;
self.display_status(status);
}
Commands::FlashEraseAllUnsecure => {
let status = self.boot.flash_erase_all_unsecure()?;
self.display_status(status);
}
Commands::FlashEraseRegion {
start_address,
byte_count,
memory_id,
} => {
let status = self.boot.flash_erase_region(start_address, byte_count, memory_id)?;
self.display_status(status);
}
Commands::WriteMemory {
start_address,
ref bytes,
memory_id,
} => {
let status = self.boot.write_memory(start_address, memory_id, bytes)?;
self.display_status(status);
}
Commands::ReceiveSbFile { ref bytes } => {
let status = self.boot.receive_sb_file(bytes)?;
self.display_status(status);
}
Commands::TrustProvisioning(ref operation) => {
let (status, data) = self.boot.trust_provisioning(operation)?;
self.display_status_words(status, &data);
self.display_trust_prov(operation, &data);
}
Commands::KeyProvisioning(ref operation) => match operation {
KeyProvOperation::SetUserKey { key_type, key_data } => {
if !self.args.silent {
debug!(
"Setting user key of type {} with {} bytes of data",
key_type,
key_data.len()
);
}
let response = self.boot.key_provisioning(operation)?;
match response {
KeyProvisioningResponse::KeyStore { status, .. } | KeyProvisioningResponse::Status(status) => {
self.display_status(status);
}
}
}
KeyProvOperation::SetKey { key_type, key_size } => {
if !self.args.silent {
debug!("Generating intrinsic key of type {key_type} with size {key_size} bytes");
}
let response = self.boot.key_provisioning(operation)?;
match response {
KeyProvisioningResponse::KeyStore { status, .. } | KeyProvisioningResponse::Status(status) => {
self.display_status(status);
}
}
}
KeyProvOperation::ReadKeyStore { file, use_hexdump } => {
debug!("Reading key store from device");
// Execute the key provisioning command
let response = self.boot.key_provisioning(operation)?;
match response {
KeyProvisioningResponse::KeyStore {
status,
response_words,
bytes,
} => {
if status.is_success() {
// Write to file
let mut output_file = File::create(file).map_err(CommunicationError::FileError)?;
output_file.write_all(&bytes)?;
if !self.args.silent {
println!("Successfully wrote {} bytes to file: {}", bytes.len(), file);
if *use_hexdump {
// Display the data in hexdump format
let cfg = HexConfig {
title: false,
group: 8,
width: 16,
ascii: true,
..HexConfig::default()
};
println!("{:?}", bytes.hex_conf(cfg));
}
}
self.display_status_words(status, &response_words);
} else {
self.display_status(status);
}
}
KeyProvisioningResponse::Status(status) => {
self.display_status(status);
}
}
}
_ => {
let response = self.boot.key_provisioning(operation)?;
match response {
KeyProvisioningResponse::KeyStore { status, .. } | KeyProvisioningResponse::Status(status) => {
self.display_status(status);
}
}
}
},
Commands::FlashReadOnce { index, count } => {
let value = self.boot.flash_read_once(index, count)?;
if !self.args.silent {
println!("Read value: {value} (0x{value:X})");
}
}
Commands::FlashProgramOnce {
index,
data,
count,
verify,
} => {
let status = self.boot.flash_program_once(index, count, data, verify)?;
self.display_status(status);
if status == StatusCode::OtpVerifyFail {
warn!("Verification failed - written value doesn't match read value");
}
}
Commands::FuseRead {
start_address,
byte_count,
ref file,
memory_id,
use_hexdump,
} => match file.as_deref() {
None | Some("-") => {
let response = self.boot.fuse_read(start_address, byte_count, memory_id)?;
self.display_memory_bytes(&response, byte_count, use_hexdump);
}
Some(file_name) => {
let response = self.boot.fuse_read(start_address, byte_count, memory_id)?;
let mut file = File::create(file_name).map_err(CommunicationError::FileError)?;
file.write_all(&response.bytes)?;
self.display_memory(&response, byte_count);
}
},
Commands::FuseProgram {
start_address,
ref file,
byte_count,
ref hex_data,
memory_id,
} => {
let bytes: Vec<u8> = if let Some(hex) = hex_data {
hex.to_vec()
} else if let Some(file_path) = file {
let mut file = File::open(file_path).map_err(CommunicationError::FileError)?;
let mut buffer = Vec::new();
match byte_count {
Some(limit) => {
buffer.resize(limit as usize, 0);
file.read_exact(&mut buffer).map_err(CommunicationError::FileError)?;
}
None => {
file.read_to_end(&mut buffer).map_err(CommunicationError::FileError)?;
}
}
buffer
} else {
return Err(CommunicationError::InvalidData);
};
let status = self.boot.fuse_program(start_address, memory_id, &bytes)?;
self.display_status(status);
}
Commands::LoadImage { ref file } => {
let mut file = File::open(file).map_err(CommunicationError::FileError)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer).map_err(CommunicationError::FileError)?;
let status = self.boot.load_image(&buffer)?;
self.display_status(status);
}
Commands::FlashImage {
ref file,
ref erase,
memory_id,
} => {
let file_path = file.clone();
let erase_option = erase.clone();
self.flash_image(&file_path, &erase_option, memory_id)?;
}
}
if self.args.secret {
println!("congratulations! you found the secret 🍨");
}
Ok(())
}
fn display_memory_bytes(&self, response: &ReadMemoryResponse, byte_count: u32, use_hexdump: bool) {
if use_hexdump {
let cfg = HexConfig {
title: false,
group: 8,
width: 16,
ascii: true,
..HexConfig::default()
};
println!("{:?}", response.bytes.hex_conf(cfg));
} else {
for byte_line in response.bytes.chunks(16) {
for byte in byte_line {
print!("{byte:02X?} ");
}
println!();
}
}
self.display_memory(response, byte_count);
}
fn display_memory(&self, response: &ReadMemoryResponse, byte_count: u32) {
self.display_status_words(response.status, &response.response_words);
if !self.args.silent {
println!("Read {} of {byte_count} bytes.", response.bytes.len());
}
}
fn display_property(&self, response: &GetPropertyResponse) {
self.display_status_words(response.status, &response.response_words);
println!("{}", response.property);
}
fn display_status_words(&self, status: StatusCode, response_words: &[u32]) {
self.display_status(status);
self.display_words(response_words);
}
fn display_words(&self, response_words: &[u32]) {
if !self.args.silent {
for (i, word) in response_words.iter().enumerate() {
let i = i + 1;
println!("Response word {i} = {word} ({word:#x})");
}
}
}
fn display_status(&self, status: StatusCode) {
if !self.args.silent {
println!("Response status = {0} ({0:#x}) {1}.", u32::from(status), status);
}
}
fn display_trust_prov(&self, operation: &TrustProvOperation, response: &[u32]) {
if !self.args.silent {
println!("Output data size/value(s) is (are):");
match operation {
TrustProvOperation::OemGenMasterShare { .. } => println!(
"\
\tOEM Share size: {0} ({0:#02X})\n\
\tOEM Master Share size: {1} ({1:#02X})\n\
\tCust Cert Puk size: {2} ({2:#02X})",
response[0], response[1], response[2]
),
TrustProvOperation::OemSetMasterShare { .. } => {}
}
}
}
fn flash_image(&mut self, image_file_path: &str, erase: &str, memory_id: u32) -> Result<(), CommunicationError> {
const ALIGNMENT: u32 = 1024;
// Validate file exists
if !Path::new(image_file_path).is_file() {
if !self.args.silent {
println!("Error: The image file does not exist: {image_file_path}");
}
return Err(CommunicationError::InvalidData);
}
// Validate erase parameter
if erase != "erase" && erase != "none" {
if !self.args.silent {
println!("Error: Invalid erase option '{erase}'. Use 'erase' or 'none'");
}
return Err(CommunicationError::InvalidData);
}
// Load and parse the image file using the ImageParser
let segments = ImageParser::parse_file(image_file_path)?;
if segments.is_empty() {
if !self.args.silent {
println!("Error: No data segments found in image file");
}
return Err(CommunicationError::InvalidData);
}
if !self.args.silent {
println!("Loaded image file: {} ({} segments)", image_file_path, segments.len());
// If it's an S-record file, show additional info
if ImageParser::is_srec_format(image_file_path)
&& let Ok((_, info)) = ImageParser::parse_srec_with_info(image_file_path)
{
if let Some(header) = &info.header {
println!(" Header: {header}");
}
println!(" Data length: {}", info.data_length);
println!(" Memory regions: {}", info.memory_regions);
}
for (i, segment) in segments.iter().enumerate() {
println!(
" Segment #{}: address=0x{:08X}, size={} bytes",
i + 1,
segment.address,
segment.data.len()
);
}
}
// Erase regions if requested
if erase == "erase" {
if !self.args.silent {
println!("Erasing flash regions...");
}
for (i, segment) in segments.iter().enumerate() {
let aligned_start = Self::align_down(segment.address, ALIGNMENT);
let aligned_end = Self::align_up(segment.address + segment.data.len() as u32, ALIGNMENT);
let aligned_length = aligned_end - aligned_start;
if !self.args.silent {
println!(
"Erasing segment #{}: address=0x{:08X}, length=0x{:08X}",
i + 1,
aligned_start,
aligned_length
);
}
let status = self.boot.flash_erase_region(aligned_start, aligned_length, memory_id)?;
if !status.is_success() {
self.display_status(status);
return Err(CommunicationError::InvalidData);
}
}
}
// Write segments
for (i, segment) in segments.iter().enumerate() {
if !self.args.silent {
println!(
"Writing segment #{}: address=0x{:08X}, size={} bytes",
i + 1,
segment.address,
segment.data.len()
);
}
let status = self.boot.write_memory(segment.address, memory_id, &segment.data)?;
if !status.is_success() {
self.display_status(status);
return Err(CommunicationError::InvalidData);
}
}
if !self.args.silent {
println!("Flash image operation completed successfully");
}
Ok(())
}
// Helper methods for alignment
fn align_down(value: u32, alignment: u32) -> u32 {
value & !(alignment - 1)
}
fn align_up(value: u32, alignment: u32) -> u32 {
(value + alignment - 1) & !(alignment - 1)
}
}