GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — esptool/esptool/cmds.py at master · espressif/esptool

Expand file tree

/

cmds.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
3680 lines (3277 loc) · 144 KB
/

cmds.py

Copy path

File metadata and controls

3680 lines (3277 loc) · 144 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: 2014-2025 Fredrik Ahlberg, Angus Gratton,
# Espressif Systems (Shanghai) CO LTD, other contributors as noted.
#
# SPDX-License-Identifier: GPL-2.0-or-later
import hashlib
import io
import itertools
import os
import struct
import sys
import time
import zlib
from typing import cast
import serial
from esp_pylib.serial_ports import get_port_names, parse_port_filters
from intelhex import IntelHex
from rich.markup import escape
from serial import SerialException
from .bin_image import (
ELFFile,
ESP32FirmwareImage,
ESP8266ROMFirmwareImage,
ESP8266V2FirmwareImage,
ESP8266V3FirmwareImage,
LoadFirmwareImage,
)
from .loader import (
DEFAULT_CONNECT_ATTEMPTS,
DEFAULT_OPEN_PORT_ATTEMPTS,
DEFAULT_TIMEOUT,
ERASE_WRITE_TIMEOUT_PER_MB,
NAND_BLOCK_SIZE,
NAND_PAGES_PER_BLOCK,
ESPLoader,
StubFlasher,
timeout_per_mb,
)
from .logger import log
from .targets import CHIP_DEFS, CHIP_LIST, ROM_LIST
from .uf2_writer import UF2Writer
from .util import (
FatalError,
ImageSource,
NANDEraseFailed,
NANDProgramFailed,
NotImplementedInROMError,
NotSupportedError,
PrintOnce,
UnsupportedCommandError,
div_roundup,
expand_chip_name,
flash_size_bytes,
get_bytes,
get_key_from_value,
hexify,
pad_to,
sanitize_string,
)
_NAND_EXPERIMENTAL_MSG = (
"NAND flash support is experimental and may change without notice."
)
_warn_nand_experimental = PrintOnce(log.warn)
# Vendors with different detection logic
ADESTO_VENDOR_ID = 0x1F
XMC_VENDOR_ID = 0x20
DETECTED_FLASH_SIZES_ADESTO = {
0x04: "512KB",
0x05: "1MB",
0x06: "2MB",
0x07: "4MB",
0x08: "8MB",
0x09: "16MB",
}
DETECTED_FLASH_SIZES = {
0x12: "256KB",
0x13: "512KB",
0x14: "1MB",
0x15: "2MB",
0x16: "4MB",
0x17: "8MB",
0x18: "16MB",
0x19: "32MB",
0x1A: "64MB",
0x1B: "128MB",
0x1C: "256MB",
0x20: "64MB",
0x21: "128MB",
0x22: "256MB",
0x32: "256KB",
0x33: "512KB",
0x34: "1MB",
0x35: "2MB",
0x36: "4MB",
0x37: "8MB",
0x38: "16MB",
0x39: "32MB",
0x3A: "64MB",
}
FLASH_MODES = {
"qio": 0,
"qout": 1,
"dio": 2,
"dout": 3,
}
# Commands for obtaining an ESP object
######################################
def detect_chip(
port: str = ESPLoader.DEFAULT_PORT,
baud: int = ESPLoader.ESP_ROM_BAUD,
connect_mode: str = "default-reset",
trace_enabled: bool = False,
connect_attempts: int = DEFAULT_CONNECT_ATTEMPTS,
) -> ESPLoader:
"""
Detect the type of ESP device connected via serial,
connect to it, and return an active ESPLoader object.
Args:
port: The serial port to use for communication.
baud: The baud rate for serial communication.
connect_mode: The chip reset method to perform when connecting to the ESP device
(``"default-reset"``, ``"usb-reset"``,
``"no-reset"``, ``"no-reset-no-sync"``)
trace_enabled: Enables or disables tracing for debugging purposes.
connect_attempts: Number of connection attempts before failing.
Returns:
An initialized instance of the detected chip class ready for use.
"""
inst = None
detect_port = ESPLoader(port, baud, trace_enabled=trace_enabled)
if detect_port.serial_port.startswith("rfc2217:"):
detect_port.USES_RFC2217 = True
detect_port.connect(connect_mode, connect_attempts, detecting=True)
def check_if_stub(instance: ESPLoader) -> ESPLoader:
log.print(f" {instance.CHIP_NAME}")
if detect_port.sync_stub_detected and instance.STUB_CLASS is not None:
instance = instance.STUB_CLASS(instance)
instance.sync_stub_detected = True
return instance
"""
First, get-security-info command is sent to detect the ID of the chip
(supported only by ESP32-C3 and later, works even in the Secure Download Mode).
If this fails, we reconnect and fall-back to reading the magic number.
It's mapped at a specific ROM address and has a different value on each chip model.
This way we use one memory read and compare it to the magic number for each chip.
"""
try:
log.print("Detecting chip type...", end="")
chip_id = detect_port.get_chip_id()
for cls in ROM_LIST:
# cmd not supported on ESP8266 and ESP32 + ESP32-S2 doesn't return chip-id
if cls.USES_MAGIC_VALUE:
continue
if chip_id == cls.IMAGE_CHIP_ID:
inst = cls(detect_port._port, baud, trace_enabled=trace_enabled)
si = inst.get_security_info()
inst.secure_download_mode = si["parsed_flags"]["SECURE_DOWNLOAD_ENABLE"]
inst = check_if_stub(inst)
inst._post_connect()
break
else:
err_msg = f"Unexpected chip ID value {chip_id}."
except (UnsupportedCommandError, FatalError):
# UnsupportedCommandError: ESP8266/ESP32 ROM
# FatalError: ESP8266/ESP32 STUB or ESP32-S2
try:
chip_magic_value = detect_port.read_reg(
ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR
)
except UnsupportedCommandError:
# Only ESP32-S2 does not support chip id detection
# and supports secure download mode
inst = CHIP_DEFS["esp32s2"](
detect_port._port, baud, trace_enabled=trace_enabled
)
si = inst.get_security_info()
inst.secure_download_mode = si["parsed_flags"]["SECURE_DOWNLOAD_ENABLE"]
inst = check_if_stub(inst)
inst._post_connect()
return inst
except FatalError:
log.print(" Autodetection failed, trying again...")
detect_port.connect(
connect_mode, connect_attempts, detecting=True, warnings=False
)
log.print("Detecting chip type...", end="")
chip_magic_value = detect_port.read_reg(
ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR
)
for cls in ROM_LIST:
if not cls.USES_MAGIC_VALUE:
continue
if chip_magic_value == cls.MAGIC_VALUE:
inst = cls(detect_port._port, baud, trace_enabled=trace_enabled)
inst = check_if_stub(inst)
inst._post_connect()
break
else:
err_msg = f"Unexpected chip magic value {chip_magic_value:#010x}."
if inst is not None:
return inst
raise FatalError(
f"{err_msg} Failed to autodetect chip type."
"\nProbably it is unsupported by this version of esptool."
)
def connect_with_retries(
port: str,
initial_baud: int,
chip: str,
max_retries: int,
trace: bool = False,
before: str = "default-reset",
) -> ESPLoader:
"""
Repeatedly attempt to open a single, known port and sync with the chip,
retrying on failure. ``connect_esp()`` is the recommended entry point;
use this lower-level helper when driving the retry loop directly.
Args:
port: The serial port to open.
initial_baud: The baud rate used when opening the port for the
initial sync (ROM bootloaders typically require 115200).
chip: Target chip name (e.g. ``"esp32"``, ``"esp32s3"``).
Must be a concrete chip, not ``"auto"``.
max_retries: Number of attempts before giving up. ``0`` retries
forever until successful.
trace: Enables or disables tracing for debugging purposes.
before: The chip reset method to perform before each attempt
(``"default-reset"``, ``"usb-reset"``,
``"no-reset"``, ``"no-reset-no-sync"``).
Returns:
A connected ESPLoader instance for the requested chip.
"""
chip_class = CHIP_DEFS[chip]
esp = None
log.print(f"Serial port {escape(str(port))}:")
first = True
ten_cycle = itertools.cycle(itertools.chain(itertools.repeat(False, 9), (True,)))
retry_loop = itertools.chain(
itertools.repeat(False, max_retries - 1),
(True,) if max_retries else itertools.cycle((False,)),
)
for last, every_tenth in zip(retry_loop, ten_cycle):
try:
esp = chip_class(port, initial_baud, trace)
if not first:
# break the retrying line
log.print("")
esp.connect(before)
return esp
except (FatalError, serial.serialutil.SerialException, OSError) as err:
if esp and esp._port:
esp._port.close()
esp = None
if first:
log.print(escape(str(err)))
log.print("Retrying failed connection", end="")
first = False
if last:
raise err
if every_tenth:
# print a dot every second
log.print(".", end="")
time.sleep(0.1)
raise AssertionError("unreachable: retry loop should return or re-raise")
def connect_first_available(
serial_list: list[str],
port: str | None,
connect_attempts: int,
initial_baud: int,
chip: str = "auto",
trace: bool = False,
before: str = "default-reset",
) -> ESPLoader | None:
"""
Iterate ``serial_list`` and return the first port that connects
successfully. ``connect_esp()`` is the recommended entry point;
use this lower-level helper when driving port iteration directly.
Args:
serial_list: Candidate serial port devices to try.
port: Original user-supplied port, or ``None`` if auto-discovering.
When set, the first connection error is re-raised instead of
being swallowed to move on to the next candidate.
connect_attempts: Number of sync attempts per candidate port.
initial_baud: The baud rate used when opening each port for the
initial sync (ROM bootloaders typically require 115200).
chip: Target chip name, or ``"auto"`` to detect.
trace: Enables or disables tracing for debugging purposes.
before: The chip reset method to perform when connecting
(``"default-reset"``, ``"usb-reset"``,
``"no-reset"``, ``"no-reset-no-sync"``).
Returns:
A connected ESPLoader instance for the first reachable port,
or ``None`` if no candidate could be connected.
"""
esp = None
for each_port in serial_list:
log.print(f"Serial port {escape(str(each_port))}:")
try:
if chip == "auto":
esp = detect_chip(
each_port, initial_baud, before, trace, connect_attempts
)
else:
chip_class = CHIP_DEFS[chip]
esp = chip_class(each_port, initial_baud, trace)
esp.connect(before, connect_attempts)
break
except (FatalError, OSError) as err:
if port is not None:
raise
log.err(f"{escape(str(each_port))} failed to connect: {escape(str(err))}")
if esp and esp._port:
esp._port.close()
esp = None
return esp
def connect_esp(
port: str | None = None,
chip: str = "auto",
initial_baud: int = ESPLoader.ESP_ROM_BAUD,
port_filter: list[str] | None = None,
before: str = "default-reset",
trace: bool = False,
connect_attempts: int = DEFAULT_CONNECT_ATTEMPTS,
open_port_attempts: int = DEFAULT_OPEN_PORT_ATTEMPTS,
) -> ESPLoader:
"""
Connect to an Espressif device, mirroring how the esptool CLI
establishes a connection: auto-discover serial ports, auto-detect
the chip, and retry failed connections.
This is the recommended single-call entry point for scripts that want
the full CLI connection behavior (port discovery, chip detection, and
reset/sync retries) without reimplementing it around ``detect_chip()``.
Args:
port: Specific serial port device to use (e.g. ``"/dev/ttyACM0"``),
or ``None`` to auto-discover ports via ``port_filter``.
chip: Target chip name (e.g. ``"esp32"``, ``"esp32s3"``),
or ``"auto"`` to detect.
initial_baud: The baud rate the port is opened at for the initial
sync, **not** an operational rate. ROM bootloaders typically
require 115200 (the default); ``connect_esp()`` does not upgrade
to a faster rate on its own — call ``esp.change_baud()`` on the
returned object afterward if you need a faster transfer speed.
port_filter: Filters applied when auto-discovering ports (ignored
when ``port`` is given), each entry of the form ``"vid=NUMBER"``,
``"pid=NUMBER"``, ``"name=SUBSTRING"`` or ``"serial=SUBSTRING"``.
before: The chip reset method to perform when connecting
(``"default-reset"``, ``"usb-reset"``,
``"no-reset"``, ``"no-reset-no-sync"``).
trace: Enables or disables tracing for debugging purposes.
connect_attempts: Number of sync attempts per candidate port
before moving on (or giving up if ``port`` was set).
open_port_attempts: Number of times to retry opening ``port``
if it fails to open. ``1`` (default) means try once; only
meaningful when both ``port`` and a concrete ``chip`` are
specified.
Returns:
A connected ``ESPLoader`` instance for the detected or requested chip.
Raises:
FatalError: If no Espressif device could be reached on any of the
candidate serial ports.
Example:
::
from esptool.cmds import connect_esp, attach_flash, run_stub
# Auto-discover the port and auto-detect the chip
with connect_esp() as esp:
esp = run_stub(esp) # Optional: upload the stub flasher
esp.change_baud(921600) # Upgrade to a faster operational rate
attach_flash(esp)
...
"""
if port is None:
try:
ser_list = get_port_names(**parse_port_filters(tuple(port_filter or [])))
except ValueError as exc:
raise FatalError(str(exc)) from exc
log.print(f"Found {len(ser_list)} serial ports...")
else:
ser_list = [port]
esp = None
if open_port_attempts != 1:
if port is None or chip == "auto":
log.warn(
"The ESPTOOL_OPEN_PORT_ATTEMPTS (open_port_attempts) option "
"can only be used with --port and --chip arguments."
)
else:
esp = connect_with_retries(
port, initial_baud, chip, open_port_attempts, trace, before
)
esp = esp or connect_first_available(
ser_list,
port=port,
connect_attempts=connect_attempts,
initial_baud=initial_baud,
chip=chip,
trace=trace,
before=before,
)
if esp is None:
raise FatalError(
"Could not connect to an Espressif device "
f"on any of the {len(ser_list)} available serial ports."
)
return esp
# Commands that require an ESP object
#####################################
def load_ram(esp: ESPLoader, input: ImageSource) -> None:
"""
Load a firmware image into RAM and execute it on the ESP device.
Args:
esp: Initiated esp object connected to a real device.
input: Path to the firmware image file, opened file-like object,
or the image data as bytes.
"""
data, source = get_bytes(input)
image = LoadFirmwareImage(esp.CHIP_NAME, data)
if esp.CHIP_NAME != "ESP8266":
error_str = _get_image_incompatibility(esp, image, source)
if error_str is not None:
log.warn(escape(f"{error_str}. The loaded image may not run."))
log.stage()
source = "image" if source is None else f"'{escape(str(source))}'"
log.print(f"Loading {source} to RAM...")
with log.progress(total=len(image.segments)) as progress:
for seg in image.segments:
size = len(seg.data)
progress.update(
advance=0,
description=f"Downloading {size} bytes at {seg.addr:#010x}",
)
esp.mem_begin(
size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, seg.addr
)
seq = 0
while len(seg.data) > 0:
esp.mem_block(seg.data[0 : esp.ESP_RAM_BLOCK], seq)
seg.data = seg.data[esp.ESP_RAM_BLOCK :]
seq += 1
progress.update(advance=1)
log.stage(finish=True)
log.print(
f"Loaded {len(image.segments)} segments from {source} to RAM, "
f"executing at {image.entrypoint:#010x}."
)
esp.mem_finish(image.entrypoint)
def verify_sdc_certificate(esp: ESPLoader, certificate: ImageSource) -> None:
"""
Verify Secure Debug Controller (SDC) certificate on the ESP device.
This function reads a certificate and verifies it against the connected
device using SDC verification commands. The certificate is used for secure
debug access control. This operation works with the ROM bootloader and does
not require the flasher stub to be loaded.
Args:
esp: Initiated esp object connected to a real device.
certificate: The SDC certificate to verify. Accepts a file path, bytes,
or an open file-like object (see ``ImageSource``).
"""
byte_data, _ = get_bytes(certificate)
# The certificate body (after the 20-byte header) begins with the USC
# config word (4 bytes, big-endian); bit 0 (USC_BIT_JTAG) requests JTAG
# re-enable. Used below to give a precise diagnostic when the device
# rejects a JTAG-enable certificate because the RE_ENABLE_JTAG_SOURCE eFuse
# selects HMAC (not the SDC) as the JTAG-re-enable source.
requests_jtag = len(byte_data) >= 24 and bool(
int.from_bytes(byte_data[20:24], "big") & 0x1
)
log.print("Verifying SDC certificate ...")
try:
esp.sdc_verify_begin(1, len(byte_data))
esp.sdc_verify_data(byte_data)
esp.sdc_verify_end() # raises FatalError if the ROM rejects the cert
except FatalError as e:
# When RE_ENABLE_JTAG_SOURCE=1 (HMAC owns JTAG re-enable) the ROM
# refuses to apply the certificate's JTAG-reuse config; that config
# check happens BEFORE the signature check and leaves the SDC command
# channel unresponsive, so esptool sees the transport drop rather than
# a clean result code. Other rejections (wrong key, chip-info, or
# session counter) return a normal error result instead. A dropped
# response while verifying a JTAG-requesting certificate therefore
# uniquely indicates the RE_ENABLE_JTAG_SOURCE=1 policy rejection.
dropped = "Serial data stream stopped" in str(
e
) or "No serial data received" in str(e)
if requests_jtag and dropped:
raise FatalError(
"SDC rejected the JTAG re-enable certificate: the device did "
"not respond after the certificate was presented. This is "
"expected when the RE_ENABLE_JTAG_SOURCE eFuse is set to 1 "
"(HMAC): HMAC, not the SDC, is then the source allowed to "
"re-enable JTAG, so the SDC cannot re-open JTAG.\n"
"To re-enable JTAG through the SDC, RE_ENABLE_JTAG_SOURCE must "
"be 0 (the default). If it is 1, use the HMAC JTAG-enable "
"workflow instead. (Certificates that do not request JTAG, "
"e.g. download-reuse or force-spi-boot, are unaffected.)"
) from e
raise
log.print("SDC certificate verified successfully.")
def read_sdc_chip_info(esp: ESPLoader, output: str = "chip_info.bin") -> None:
"""
Read Secure Debug Controller (SDC) chip info from the device.
This function sends a random nonce to the device, which uses it to compute
chip-specific information via the SDC generation commands. The chip info
(32 bytes) read back is appended with the nonce (32 bytes) to create a
64-byte output file. The chip info can be used for secure debug certificate
generation. This operation works with the ROM bootloader and does not
require the flasher stub to be loaded.
Args:
esp: Initiated esp object connected to a real device.
output: Output filename for the chip info binary file
(defaults to "chip_info.bin").
"""
log.print("Reading SDC chip info ...")
# Generate random 32-byte nonce
nonce = os.urandom(32)
log.debug(f"Generated random nonce ({len(nonce)} bytes): {nonce.hex()}")
esp.sdc_gen_begin()
esp.sdc_gen_data(nonce)
chip_info = esp.sdc_gen_end()
if chip_info is None or len(chip_info) != 32:
raise FatalError("Failed to generate chip info or invalid chip info size")
log.debug(f"Generated chip info ({len(chip_info)} bytes): {chip_info.hex()}")
# Write chip_info + nonce (chip_info = 32 bytes, nonce = 32 bytes, total = 64 bytes)
# Format: chip_info (first 32 bytes) + nonce (last 32 bytes)
combined_data = chip_info + nonce
with open(output, "wb") as f:
f.write(combined_data)
log.print(f"Chip info is saved to {escape(str(output))}!")
def read_mem(esp: ESPLoader, address: int) -> None:
"""
Read and display a 32-bit value from a memory address on the ESP device.
Args:
esp: Initiated esp object connected to a real device.
address: Memory address to read from (32-bit aligned).
"""
log.print(f"{address:#010x} = {esp.read_reg(address):#010x}")
def write_mem(esp: ESPLoader, address: int, value: int, mask: int = 0xFFFFFFFF) -> None:
"""
Write a 32-bit value to a memory address on the ESP device with optional bitmask.
Args:
esp: Initiated esp object connected to a real device.
address: Memory address to write to (32-bit aligned).
value: 32-bit value to write.
mask: Bitmask specifying which bits to modify (default: all bits).
"""
esp.write_reg(address, value, mask, 0)
log.print(f"Wrote {value:#010x} with mask {mask:#010x} to {address:#010x}.")
def dump_mem(
esp: ESPLoader, address: int, size: int, output: str | None = None
) -> bytes | None:
"""
Dump a block of memory from the ESP device.
Args:
esp: Initiated esp object connected to a real device.
address: Starting memory address to dump from.
size: Number of bytes to dump.
output: Path to output file for binary data. If None, returns the data.
Returns:
Memory dump as bytes if output is None;
otherwise, returns None after writing to file.
"""
data = io.BytesIO() # Use BytesIO to store the memory dump
log.stage()
log.print(
f"Dumping {size} bytes from {address:#010x}"
+ (f" to file '{escape(str(output))}'..." if output else "...")
)
t = time.time()
# Read the memory in 4-byte chunks.
with log.progress(total=size, unit="B") as progress:
last = 0
for i in range(size // 4):
cur_addr = address + (i * 4)
d = esp.read_reg(cur_addr)
data.write(struct.pack("<I", d)) # Write 4 bytes to BytesIO
# Update progress every 1024 bytes.
cur = data.tell()
if cur % 1024 == 0 or cur == size:
progress.update(
advance=cur - last,
description=f"Dumping from {cur_addr:#010x}",
)
last = cur
t = time.time() - t
speed_msg = " ({:.1f} kbit/s)".format(data.tell() / t * 8 / 1000) if t > 0.0 else ""
dest_msg = f" to '{escape(str(output))}'" if output else ""
log.stage(finish=True)
log.print(
f"Dumped {data.tell()} bytes from {address:#010x} in {t:.1f} seconds"
f"{speed_msg}{dest_msg}."
)
if output:
with open(output, "wb") as f:
f.write(data.getvalue())
return None
else:
return data.getvalue()
def _get_flash_info(esp: ESPLoader, cache: bool = True) -> tuple[int, int, str | None]:
"""
Get the flash memory chip information including vendor ID, device ID, and
flash size.
Args:
esp: Initiated esp object connected to a real device.
cache: Whether to use cached flash ID (default: True).
Returns:
Tuple containing (vendor_id, device_id, flash_size)
"""
flash_id = esp.flash_id(cache=cache)
vendor_id = flash_id & 0xFF
# Swap the bytes of the device ID by taking the high byte first, then the low byte
device_id = ((flash_id >> 16) & 0xFF) | ((flash_id >> 8) & 0xFF) << 8
if vendor_id == ADESTO_VENDOR_ID:
# Lower 5 bits of second byte of flash_id is size_id
size_id = (flash_id >> 8) & 0x1F
flash_size = DETECTED_FLASH_SIZES_ADESTO.get(size_id)
else:
size_id = flash_id >> 16
flash_size = DETECTED_FLASH_SIZES.get(size_id)
return vendor_id, device_id, flash_size
def detect_flash_size(esp: ESPLoader) -> str | None:
"""
Detect the flash size of the connected ESP device.
Args:
esp: Initiated esp object connected to a real device.
Returns:
Detected flash size in bytes, or None if unrecognized.
"""
if esp.secure_download_mode:
raise FatalError(
"Detecting flash size is not supported in secure download mode. "
"Need to manually specify flash size."
)
_, _, flash_size = _get_flash_info(esp)
return flash_size
def _update_image_flash_params(esp, address, flash_freq, flash_mode, flash_size, image):
"""
Update the flash mode, size, and freq parameters in a bootloader image,
if applicable.
Args:
esp (ESPLoader): ESPLoader object that provides device-specific attributes
(e.g., BOOTLOADER_FLASH_OFFSET, ESP_IMAGE_MAGIC, CHIP_NAME) and methods for
image verification and parameter parsing.
address (int): The flash memory address where the image is to be written.
flash_freq (str, optional): Flash frequency setting
(``"keep"`` to retain current).
flash_mode (str, optional): Flash mode setting
(``"keep"`` to retain current).
flash_size (str, optional): Flash size setting
(``"keep"`` to retain current).
image (bytes): The image data that may contain an executable bootloader image.
Returns:
bytes: The modified image data with updated flash parameters
(and recalculated SHA256 digest, if applicable),
or the original image if no modifications were performed.
"""
if len(image) < 8:
return image # not long enough to be a bootloader image
if address != esp.BOOTLOADER_FLASH_OFFSET:
return image # not flashing bootloader offset, so don't modify this
if (flash_mode, flash_freq, flash_size) == ("keep",) * 3:
return image # all settings are 'keep', not modifying anything
# unpack the (potential) image header
magic, _, img_flash_mode, img_flash_size_freq = struct.unpack("BBBB", image[:4])
# easy check if this is an image: does it start with a magic byte?
if magic != esp.ESP_IMAGE_MAGIC:
log.warn(
f"Image file at {address:#x} doesn't look like an image file, "
"so not changing any flash settings."
)
return image
# make sure this really is an image, and not just data that
# starts with esp.ESP_IMAGE_MAGIC (mostly a problem for encrypted
# images that happen to start with a magic byte
try:
test_image = esp.BOOTLOADER_IMAGE(io.BytesIO(image))
test_image.verify()
except Exception:
log.warn(
f"Image file at {address:#x} is not a valid {esp.CHIP_NAME} image,"
" so not changing any flash settings."
)
return image
# After the 8-byte header comes the extended header for chips others than ESP8266.
# The 15th byte of the extended header indicates if the image is protected by SHA256
# checksum. In that case we recalculate the SHA digest after modifying the header.
sha_appended = esp.CHIP_NAME != "esp8266" and image[8 + 15] == 1
if flash_mode != "keep":
img_flash_mode = FLASH_MODES[flash_mode]
img_flash_freq = img_flash_size_freq & 0x0F
if flash_freq != "keep":
img_flash_freq = esp.parse_flash_freq_arg(flash_freq)
img_flash_size = img_flash_size_freq & 0xF0
if flash_size != "keep":
img_flash_size = esp.parse_flash_size_arg(flash_size)
flash_params = struct.pack(b"BB", img_flash_mode, img_flash_size + img_flash_freq)
if flash_params != image[2:4]:
log.print(
f"Flash parameters set to {struct.unpack('>H', flash_params)[0]:#06x}."
)
image = image[0:2] + flash_params + image[4:]
# recalculate the SHA digest if it was appended
if sha_appended:
# Since the changes are only made for images located in the bootloader offset,
# we can assume that the image is always a bootloader image.
# For merged binaries, we check the bootloader SHA when parameters are changed.
image_object = esp.BOOTLOADER_IMAGE(io.BytesIO(image))
# get the image header, extended header (if present) and data
image_data_before_sha = image[: image_object.data_length]
# get the image data after the SHA digest (primary for merged binaries)
image_data_after_sha = image[
(image_object.data_length + image_object.SHA256_DIGEST_LEN) :
]
sha_digest_calculated = hashlib.sha256(image_data_before_sha).digest()
image = bytes(
itertools.chain(
image_data_before_sha, sha_digest_calculated, image_data_after_sha
)
)
# get SHA digest newly stored in the image and compare it to the calculated one
image_stored_sha = image[
image_object.data_length : image_object.data_length
+ image_object.SHA256_DIGEST_LEN
]
if hexify(sha_digest_calculated) == hexify(image_stored_sha):
log.print("SHA digest in image updated.")
else:
log.warn(
"SHA recalculation for binary failed!\n"
f"\tExpected calculated SHA: {hexify(sha_digest_calculated)}\n"
f"\tSHA stored in binary: {hexify(image_stored_sha)}"
)
return image
def _diff_flash_regions(
old_image: bytes,
new_image: bytes,
start_address: int,
) -> list[tuple[int, bytes]]:
"""
Diff two images and return flash write payloads for changed flash sectors.
- Bytes are compared up to the next flash sector boundary after the new_image end.
Bytes past the end of new_image (within the final sector) are treated as 0xFF.
We don't care about any sectors fully past the end of new_image, these will not
trigger reflashing.
- Missing bytes in old_image (old shorter than new) are treated as 0xFF.
- Payloads are sector-aligned and padded with 0xFF
(no bytes from old image are preserved).
"""
if len(new_image) == 0:
return []
# Compare only up to the next sector boundary after new_image.
# Example: len(new_image)=5000 -> compare_len=8192 (2 sectors).
compare_len = (
div_roundup(len(new_image), ESPLoader.FLASH_SECTOR_SIZE)
* ESPLoader.FLASH_SECTOR_SIZE
)
changed_sectors: set[int] = set()
for offset in range(compare_len):
# Treat missing old bytes or new bytes beyond the end of the new_image as 0xFF.
a = old_image[offset] if offset < len(old_image) else 0xFF
b = new_image[offset] if offset < len(new_image) else 0xFF
if a != b:
# Calculate the flash address of the changed byte.
flash_addr = start_address + offset
# Round down to sector start. Example: 0x1002 -> 0x1000.
changed_sectors.add(flash_addr & ~(ESPLoader.FLASH_SECTOR_SIZE - 1))
if not changed_sectors:
return []
# Merge consecutive sectors into larger ranges to reduce flash_begin overhead.
# Example: sectors [0x4000, 0x5000, 0x6000] -> ranges [(0x4000, 0x3000)].
sorted_sectors = sorted(changed_sectors)
ranges: list[tuple[int, int]] = []
run_start = sorted_sectors[0]
run_end = run_start + ESPLoader.FLASH_SECTOR_SIZE
for s in sorted_sectors[1:]:
if s == run_end:
run_end += ESPLoader.FLASH_SECTOR_SIZE
else:
ranges.append((run_start, run_end - run_start))
run_start = s
run_end = s + ESPLoader.FLASH_SECTOR_SIZE
ranges.append((run_start, run_end - run_start)) # Add (area_addr, area_size)
# Create payloads for each changed flash region (one or more consecutive sectors).
regions: list[tuple[int, bytes]] = []
for area_addr, area_size in ranges:
area_end = area_addr + area_size
# Start with 0xFF, we will overlay the new_image bytes over this.
data = bytearray(b"\xff" * area_size)
# Overlay bytes from new image; bytes beyond len(new_image) stay 0xFF.
# Example: area 0x1000..0x2000, start_address=0x1000, len(new_image)=5000
# -> new_start=0x1000, new_end=0x2000 (min of 0x2000 and 0x1000+5000).
new_start = max(area_addr, start_address)
new_end = min(area_end, start_address + len(new_image))
if new_start >= new_end:
# Entire range is beyond new_image; should not happen as compare_len
# stops at the next sector boundary after new_image.
continue
src_off = new_start - start_address # offset into new_image
dst_off = new_start - area_addr # offset into this payload
data[dst_off : dst_off + (new_end - new_start)] = new_image[
src_off : src_off + (new_end - new_start)
]
regions.append((area_addr, bytes(data)))
return regions
def _read_flash_nand_with_skip(
esp: ESPLoader,
address: int,
size: int,
progress_fn=None,
nand_end_address: int | None = None,
) -> bytes:
"""
Read ``size`` bytes of logical data from NAND flash starting at logical
``address``, skipping bad blocks. Bad blocks are detected via the first
spare byte of each block's first page (0xFF = good). Only data from good
blocks is included in the returned buffer; the caller receives contiguous
logical data exactly ``size`` bytes long.
Raises FatalError if the end of the addressable range is reached before
``size`` bytes of good-block data have been accumulated.
"""
if nand_end_address is None:
nand_end_address = NAND_TOTAL_SIZE
accumulated = b""
phys_addr = address
while len(accumulated) < size:
if phys_addr >= nand_end_address:
raise FatalError(
f"Reached NAND end address {nand_end_address:#x} before reading the "
f"requested {size} bytes; remaining good blocks exhausted."
)
# Check bad-block marker for this physical block
page_num = phys_addr // NAND_BLOCK_SIZE * NAND_PAGES_PER_BLOCK
bb = esp.read_nand_spare(page_num) & 0xFF
if bb != 0xFF:
log.print(f"Skipping bad block at {phys_addr:#010x} during read")
phys_addr += NAND_BLOCK_SIZE
if phys_addr >= nand_end_address:
raise FatalError(
f"Reached NAND end address {nand_end_address:#x} before reading "
f"the requested {size} bytes; remaining good blocks exhausted."
)
continue
remaining = size - len(accumulated)
read_size = min(NAND_BLOCK_SIZE - (phys_addr % NAND_BLOCK_SIZE), remaining)
chunk = esp.read_flash_nand(phys_addr, read_size, None)
accumulated += chunk
if progress_fn is not None:
progress_fn(len(accumulated), size, address)
phys_addr += read_size
return accumulated[:size]
def _count_good_blocks(esp, start_addr, end_addr, needed):
"""Return min(good_blocks, needed) between [start_addr, end_addr).
Stops early once `needed` good blocks are found (matches existing pre-scan
behaviour).
"""
good = 0
addr = start_addr
while addr < end_addr:
page_num = addr // NAND_BLOCK_SIZE * NAND_PAGES_PER_BLOCK
if esp.read_nand_spare(page_num) & 0xFF == 0xFF:
good += 1
if good >= needed:
break
addr += NAND_BLOCK_SIZE
return good
def _write_flash_nand(
esp: ESPLoader, addr_data: list[tuple[int, ImageSource]], **kwargs
) -> None:
"""
Write firmware or data to NAND flash memory (internal helper).
NAND flash writing has different logic due to bad block management.
Uses stub commands ESP_SPI_NAND_WRITE_FLASH_BEGIN / ESP_SPI_NAND_WRITE_FLASH_DATA.
"""
_warn_nand_experimental(_NAND_EXPERIMENTAL_MSG)
BLOCK_SIZE = NAND_BLOCK_SIZE
no_progress: bool = kwargs.get("no_progress", False)
View remainder of file in raw view
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.