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
//! ESP32 flash target module.
//!
//! This module defines the traits and types used for flashing operations on a
//! target device's flash memory.
use std::io::Write;
use flate2::{
Compression,
write::{ZlibDecoder, ZlibEncoder},
};
use log::debug;
use md5::{Digest, Md5};
use crate::{
Error,
flasher::{FLASH_SECTOR_SIZE, SpiAttachParams},
image_format::Segment,
target::{Chip, WDT_WKEY},
};
#[cfg(feature = "serialport")]
use crate::{
command::{Command, CommandType},
connection::Connection,
target::FlashTarget,
target::ProgressCallbacks,
};
/// Applications running from an ESP32's (or variant's) flash
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct Esp32Target {
chip: Chip,
spi_attach_params: SpiAttachParams,
use_stub: bool,
verify: bool,
skip: bool,
need_flash_end: bool,
}
impl Esp32Target {
/// Create a new ESP32 target.
pub fn new(
chip: Chip,
spi_attach_params: SpiAttachParams,
use_stub: bool,
verify: bool,
skip: bool,
) -> Self {
Esp32Target {
chip,
spi_attach_params,
use_stub,
verify,
skip,
need_flash_end: false,
}
}
}
#[cfg(feature = "serialport")]
impl FlashTarget for Esp32Target {
fn begin(&mut self, connection: &mut Connection) -> Result<(), Error> {
connection.with_timeout(CommandType::SpiAttach.timeout(), |connection| {
let command = if self.use_stub {
Command::SpiAttachStub {
spi_params: self.spi_attach_params,
}
} else {
Command::SpiAttach {
spi_params: self.spi_attach_params,
}
};
connection.command(command)
})?;
// The stub usually disables these watchdog timers, however if we're not using
// the stub we need to disable them before flashing begins.
//
// TODO: the stub doesn't appear to disable the watchdog on ESP32-S3, so we
// explicitly disable the watchdog here.
//
// NOTE: In Secure Download Mode, WRITE_REG commands are not allowed, so we
// must skip the watchdog disable.
if connection.is_using_usb_serial_jtag()
&& !connection.secure_download_mode
&& let (Some(wdt_wprotect), Some(wdt_config0)) =
(self.chip.wdt_wprotect(), self.chip.wdt_config0())
{
connection.command(Command::WriteReg {
address: wdt_wprotect,
value: WDT_WKEY,
mask: None,
})?; // WP disable
connection.command(Command::WriteReg {
address: wdt_config0,
value: 0x0,
mask: None,
})?; // turn off RTC WDT
connection.command(Command::WriteReg {
address: wdt_wprotect,
value: 0x0,
mask: None,
})?; // WP enable
}
Ok(())
}
fn write_segment(
&mut self,
connection: &mut Connection,
segment: Segment<'_>,
progress: &mut dyn ProgressCallbacks,
) -> Result<(), Error> {
let addr = segment.addr;
let mut md5_hasher = Md5::new();
md5_hasher.update(&segment.data);
let checksum_md5 = md5_hasher.finalize();
// use compression only when stub is loaded.
let use_compression = self.use_stub;
let flash_write_size = if self.use_stub {
self.chip.stub_flash_write_size()
} else {
self.chip.flash_write_size()
};
let erase_count = segment.data.len().div_ceil(FLASH_SECTOR_SIZE);
// round up to sector size
let erase_size = (erase_count * FLASH_SECTOR_SIZE) as u32;
if self.skip {
let flash_checksum_md5: u128 = connection.with_timeout(
CommandType::FlashMd5.timeout_for_size(segment.data.len() as u32),
|connection| {
connection
.command(Command::FlashMd5 {
offset: addr,
size: segment.data.len() as u32,
})?
.try_into()
},
)?;
if checksum_md5[..] == flash_checksum_md5.to_be_bytes() {
debug!("Segment at address '0x{addr:x}' has not changed, skipping write");
progress.finish(true);
return Ok(());
}
}
let data = if use_compression {
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
encoder.write_all(&segment.data)?;
encoder.finish()?
} else {
segment.data.to_vec()
};
let block_count = data.len().div_ceil(flash_write_size);
let chunks = data.chunks(flash_write_size);
let num_chunks = chunks.len();
progress.init(addr, num_chunks);
if use_compression {
connection.with_timeout(
CommandType::FlashDeflBegin.timeout_for_size(erase_size),
|connection| {
connection.command(Command::FlashDeflBegin {
size: segment.data.len() as u32,
blocks: block_count as u32,
block_size: flash_write_size as u32,
offset: addr,
supports_encryption: self.chip != Chip::Esp32 && !self.use_stub,
})?;
Ok(())
},
)?;
} else {
connection.with_timeout(
CommandType::FlashBegin.timeout_for_size(erase_size),
|connection| {
connection.command(Command::FlashBegin {
size: erase_size,
blocks: block_count as u32,
block_size: flash_write_size as u32,
offset: addr,
supports_encryption: self.chip != Chip::Esp32,
})?;
Ok(())
},
)?;
}
self.need_flash_end = true;
// decode the chunks to see how much data the device will have to save
let mut decoder = ZlibDecoder::new(Vec::new());
let mut decoded_size = 0;
for (i, block) in chunks.enumerate() {
if use_compression {
decoder.write_all(block)?;
decoder.flush()?;
let size = decoder.get_ref().len() - decoded_size;
decoded_size = decoder.get_ref().len();
connection.with_timeout(
CommandType::FlashDeflData.timeout_for_size(size as u32),
|connection| {
connection.command(Command::FlashDeflData {
sequence: i as u32,
pad_to: 0,
pad_byte: 0xff,
data: block,
})?;
Ok(())
},
)?;
} else {
connection.with_timeout(
CommandType::FlashData.timeout_for_size(block.len() as u32),
|connection| {
connection.command(Command::FlashData {
sequence: i as u32,
pad_to: flash_write_size,
pad_byte: 0xff,
data: block,
})?;
Ok(())
},
)?;
}
progress.update(i + 1)
}
if self.verify {
progress.verifying();
let flash_checksum_md5: u128 = connection.with_timeout(
CommandType::FlashMd5.timeout_for_size(segment.data.len() as u32),
|connection| {
connection
.command(Command::FlashMd5 {
offset: addr,
size: segment.data.len() as u32,
})?
.try_into()
},
)?;
if checksum_md5[..] != flash_checksum_md5.to_be_bytes() {
return Err(Error::VerifyFailed);
}
debug!("Segment at address '0x{addr:x}' verified successfully");
}
progress.finish(false);
Ok(())
}
fn finish(&mut self, connection: &mut Connection, reboot: bool) -> Result<(), Error> {
if self.need_flash_end {
// In Secure Download Mode, "run user code" (reboot: false) makes the ROM
// verify/run the flashed image, which fails for unsigned images.
// "Reboot" (reboot: true) only finalizes the write and reboots,
// avoiding that error.
let flash_end_reboot = connection.secure_download_mode || reboot;
let result = if self.use_stub {
// Let the host-side reset path handle rebooting after stub flashing. Asking the
// stub to reboot from FLASH_DEFL_END can race with response handling on some
// ESP32-P4 revisions/stubs, while the command's non-reboot path just exits
// flash mode.
connection.with_timeout(CommandType::FlashDeflEnd.timeout(), |connection| {
connection.command(Command::FlashDeflEnd { reboot: false })
})
} else {
connection.with_timeout(CommandType::FlashEnd.timeout(), |connection| {
connection.command(Command::FlashEnd {
reboot: flash_end_reboot,
})
})
};
match result {
Ok(_) => {}
Err(Error::RomError(_)) if connection.secure_download_mode => {
// In SDM the ROM may still return an error for FlashEnd
// (e.g. digest verification failed for
// unsigned image). The data was written; treat as success.
}
Err(e) => return Err(e),
}
}
if reboot && !connection.secure_download_mode {
connection.reset_after(self.use_stub, self.chip)?;
}
Ok(())
}
}