id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,289,600 | __main__.py | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/__main__.py | # SPDX-FileCopyrightText: 2014-2022 Fredrik Ahlberg, Angus Gratton,
# Espressif Systems (Shanghai) CO LTD, other contributors as noted.
#
# SPDX-License-Identifier: GPL-2.0-or-later
import esptool
if __name__ == "__main__":
esptool._main()
| 246 | Python | .py | 7 | 33.285714 | 67 | 0.738397 | OLIMEX/RVPC | 8 | 2 | 1 | GPL-3.0 | 9/5/2024, 10:48:43 PM (Europe/Amsterdam) |
2,289,601 | util.py | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/util.py | # SPDX-FileCopyrightText: 2014-2022 Fredrik Ahlberg, Angus Gratton,
# Espressif Systems (Shanghai) CO LTD, other contributors as noted.
#
# SPDX-License-Identifier: GPL-2.0-or-later
import os
import re
import struct
import sys
def byte(bitstr, index):
return bitstr[index]
def mask_to_shift(mask):
"""Return the index of the least significant bit in the mask"""
shift = 0
while mask & 0x1 == 0:
shift += 1
mask >>= 1
return shift
def div_roundup(a, b):
"""Return a/b rounded up to nearest integer,
equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
without possible floating point accuracy errors.
"""
return (int(a) + int(b) - 1) // int(b)
def flash_size_bytes(size):
"""Given a flash size of the type passed in args.flash_size
(ie 512KB or 1MB) then return the size in bytes.
"""
if size is None:
return None
if "MB" in size:
return int(size[: size.index("MB")]) * 1024 * 1024
elif "KB" in size:
return int(size[: size.index("KB")]) * 1024
else:
raise FatalError("Unknown size %s" % size)
def hexify(s, uppercase=True):
format_str = "%02X" if uppercase else "%02x"
return "".join(format_str % c for c in s)
def pad_to(data, alignment, pad_character=b"\xFF"):
"""Pad to the next alignment boundary"""
pad_mod = len(data) % alignment
if pad_mod != 0:
data += pad_character * (alignment - pad_mod)
return data
def print_overwrite(message, last_line=False):
"""Print a message, overwriting the currently printed line.
If last_line is False, don't append a newline at the end
(expecting another subsequent call will overwrite this one.)
After a sequence of calls with last_line=False, call once with last_line=True.
If output is not a TTY (for example redirected a pipe),
no overwriting happens and this function is the same as print().
"""
if sys.stdout.isatty():
print("\r%s" % message, end="\n" if last_line else "")
else:
print(message)
def expand_chip_name(chip_name):
"""Change chip name to official form, e.g. `esp32s3beta2` -> `ESP32-S3(beta2)`"""
# Put "-" after "esp32"
chip_name = re.sub(r"(esp32)(?!$)", r"\1-", chip_name)
# Put "()" around "betaN"
chip_name = re.sub(r"(beta\d*)", r"(\1)", chip_name)
# Uppercase everything before "(betaN)"
chip_name = re.sub(r"^[^\(]+", lambda x: x.group(0).upper(), chip_name)
return chip_name
def strip_chip_name(chip_name):
"""Strip chip name to normalized form, e.g. `ESP32-S3(beta2)` -> `esp32s3beta2`"""
return re.sub(r"[-()]", "", chip_name.lower())
def get_file_size(path_to_file):
"""Returns the file size in bytes"""
file_size = 0
with open(path_to_file, "rb") as f:
f.seek(0, os.SEEK_END)
file_size = f.tell()
return file_size
class FatalError(RuntimeError):
"""
Wrapper class for runtime errors that aren't caused by internal bugs, but by
ESP ROM responses or input content.
"""
def __init__(self, message):
RuntimeError.__init__(self, message)
@staticmethod
def WithResult(message, result):
"""
Return a fatal error object that appends the hex values of
'result' and its meaning as a string formatted argument.
"""
err_defs = {
# ROM error codes
0x101: "Out of memory",
0x102: "Invalid argument",
0x103: "Invalid state",
0x104: "Invalid size",
0x105: "Requested resource not found",
0x106: "Operation or feature not supported",
0x107: "Operation timed out",
0x108: "Received response was invalid",
0x109: "CRC or checksum was invalid",
0x10A: "Version was invalid",
0x10B: "MAC address was invalid",
# Flasher stub error codes
0xC000: "Bad data length",
0xC100: "Bad data checksum",
0xC200: "Bad blocksize",
0xC300: "Invalid command",
0xC400: "Failed SPI operation",
0xC500: "Failed SPI unlock",
0xC600: "Not in flash mode",
0xC700: "Inflate error",
0xC800: "Not enough data",
0xC900: "Too much data",
0xFF00: "Command not implemented",
}
err_code = struct.unpack(">H", result[:2])
message += " (result was {}: {})".format(
hexify(result), err_defs.get(err_code[0], "Unknown result")
)
return FatalError(message)
class NotImplementedInROMError(FatalError):
"""
Wrapper class for the error thrown when a particular ESP bootloader function
is not implemented in the ROM bootloader.
"""
def __init__(self, bootloader, func):
FatalError.__init__(
self,
"%s ROM does not support function %s."
% (bootloader.CHIP_NAME, func.__name__),
)
class NotSupportedError(FatalError):
def __init__(self, esp, function_name):
FatalError.__init__(
self,
"Function %s is not supported for %s." % (function_name, esp.CHIP_NAME),
)
class UnsupportedCommandError(RuntimeError):
"""
Wrapper class for when ROM loader returns an invalid command response.
Usually this indicates the loader is running in Secure Download Mode.
"""
def __init__(self, esp, op):
if esp.secure_download_mode:
msg = "This command (0x%x) is not supported in Secure Download Mode" % op
else:
msg = "Invalid (unsupported) command 0x%x" % op
RuntimeError.__init__(self, msg)
| 5,713 | Python | .py | 147 | 31.666667 | 86 | 0.618057 | OLIMEX/RVPC | 8 | 2 | 1 | GPL-3.0 | 9/5/2024, 10:48:43 PM (Europe/Amsterdam) |
2,289,602 | config.py | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/config.py | # SPDX-FileCopyrightText: 2014-2023 Espressif Systems (Shanghai) CO LTD,
# other contributors as noted.
#
# SPDX-License-Identifier: GPL-2.0-or-later
import configparser
import os
CONFIG_OPTIONS = [
"timeout",
"chip_erase_timeout",
"max_timeout",
"sync_timeout",
"md5_timeout_per_mb",
"erase_region_timeout_per_mb",
"erase_write_timeout_per_mb",
"mem_end_rom_timeout",
"serial_write_timeout",
"connect_attempts",
"write_block_attempts",
"reset_delay",
"custom_reset_sequence",
]
def _validate_config_file(file_path, verbose=False):
if not os.path.exists(file_path):
return False
cfg = configparser.RawConfigParser()
try:
cfg.read(file_path, encoding="UTF-8")
# Only consider it a valid config file if it contains [esptool] section
if cfg.has_section("esptool"):
if verbose:
unknown_opts = list(set(cfg.options("esptool")) - set(CONFIG_OPTIONS))
unknown_opts.sort()
no_of_unknown_opts = len(unknown_opts)
if no_of_unknown_opts > 0:
suffix = "s" if no_of_unknown_opts > 1 else ""
print(
"Ignoring unknown config file option{}: {}".format(
suffix, ", ".join(unknown_opts)
)
)
return True
except (UnicodeDecodeError, configparser.Error) as e:
if verbose:
print(f"Ignoring invalid config file {file_path}: {e}")
return False
def _find_config_file(dir_path, verbose=False):
for candidate in ("esptool.cfg", "setup.cfg", "tox.ini"):
cfg_path = os.path.join(dir_path, candidate)
if _validate_config_file(cfg_path, verbose):
return cfg_path
return None
def load_config_file(verbose=False):
set_with_env_var = False
env_var_path = os.environ.get("ESPTOOL_CFGFILE")
if env_var_path is not None and _validate_config_file(env_var_path):
cfg_file_path = env_var_path
set_with_env_var = True
else:
home_dir = os.path.expanduser("~")
os_config_dir = (
f"{home_dir}/.config/esptool"
if os.name == "posix"
else f"{home_dir}/AppData/Local/esptool/"
)
# Search priority: 1) current dir, 2) OS specific config dir, 3) home dir
for dir_path in (os.getcwd(), os_config_dir, home_dir):
cfg_file_path = _find_config_file(dir_path, verbose)
if cfg_file_path:
break
cfg = configparser.ConfigParser()
cfg["esptool"] = {} # Create an empty esptool config for when no file is found
if cfg_file_path is not None:
# If config file is found and validated, read and parse it
cfg.read(cfg_file_path)
if verbose:
msg = " (set with ESPTOOL_CFGFILE)" if set_with_env_var else ""
print(
f"Loaded custom configuration from "
f"{os.path.abspath(cfg_file_path)}{msg}"
)
return cfg, cfg_file_path
| 3,106 | Python | .py | 81 | 29.308642 | 86 | 0.593232 | OLIMEX/RVPC | 8 | 2 | 1 | GPL-3.0 | 9/5/2024, 10:48:43 PM (Europe/Amsterdam) |
2,289,603 | cmds.py | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/cmds.py | # SPDX-FileCopyrightText: 2014-2022 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 os
import struct
import sys
import time
import zlib
from .bin_image import ELFFile, ImageSegment, LoadFirmwareImage
from .bin_image import (
ESP8266ROMFirmwareImage,
ESP8266V2FirmwareImage,
ESP8266V3FirmwareImage,
)
from .loader import (
DEFAULT_CONNECT_ATTEMPTS,
DEFAULT_TIMEOUT,
ERASE_WRITE_TIMEOUT_PER_MB,
ESPLoader,
timeout_per_mb,
)
from .targets import CHIP_DEFS, CHIP_LIST, ROM_LIST
from .util import (
FatalError,
NotImplementedInROMError,
NotSupportedError,
UnsupportedCommandError,
)
from .util import (
div_roundup,
flash_size_bytes,
get_file_size,
hexify,
pad_to,
print_overwrite,
)
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}
def detect_chip(
port=ESPLoader.DEFAULT_PORT,
baud=ESPLoader.ESP_ROM_BAUD,
connect_mode="default_reset",
trace_enabled=False,
connect_attempts=DEFAULT_CONNECT_ATTEMPTS,
):
"""Use serial access to detect the chip type.
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.
This routine automatically performs ESPLoader.connect() (passing
connect_mode parameter) as part of querying the chip.
"""
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)
try:
print("Detecting chip type...", end="")
chip_id = detect_port.get_chip_id()
for cls in [
n for n in ROM_LIST if n.CHIP_NAME not in ("ESP8266", "ESP32", "ESP32-S2")
]:
# cmd not supported on ESP8266 and ESP32 + ESP32-S2 doesn't return chip_id
if chip_id == cls.IMAGE_CHIP_ID:
inst = cls(detect_port._port, baud, trace_enabled=trace_enabled)
try:
inst.read_reg(
ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR
) # Dummy read to check Secure Download mode
except UnsupportedCommandError:
inst.secure_download_mode = True
inst._post_connect()
break
else:
err_msg = f"Unexpected chip ID value {chip_id}."
except (UnsupportedCommandError, struct.error, FatalError) as e:
# UnsupportedCommmanddError: ESP8266/ESP32 ROM
# struct.error: ESP32-S2
# FatalError: ESP8266/ESP32 STUB
print(" Unsupported detection protocol, switching and trying again...")
try:
# ESP32/ESP8266 are reset after an unsupported command, need to reconnect
# (not needed on ESP32-S2)
if not isinstance(e, struct.error):
detect_port.connect(
connect_mode, connect_attempts, detecting=True, warnings=False
)
print("Detecting chip type...", end="")
sys.stdout.flush()
chip_magic_value = detect_port.read_reg(
ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR
)
for cls in ROM_LIST:
if chip_magic_value in cls.CHIP_DETECT_MAGIC_VALUE:
inst = cls(detect_port._port, baud, trace_enabled=trace_enabled)
inst._post_connect()
inst.check_chip_id()
break
else:
err_msg = f"Unexpected chip magic value {chip_magic_value:#010x}."
except UnsupportedCommandError:
raise FatalError(
"Unsupported Command Error received. "
"Probably this means Secure Download Mode is enabled, "
"autodetection will not work. Need to manually specify the chip."
)
finally:
if inst is not None:
print(" %s" % inst.CHIP_NAME, end="")
if detect_port.sync_stub_detected:
inst = inst.STUB_CLASS(inst)
inst.sync_stub_detected = True
print("") # end line
return inst
raise FatalError(
f"{err_msg} Failed to autodetect chip type."
"\nProbably it is unsupported by this version of esptool."
)
# "Operation" commands, executable at command line. One function each
#
# Each function takes either two args (<ESPLoader instance>, <args>) or a single <args>
# argument.
def load_ram(esp, args):
image = LoadFirmwareImage(esp.CHIP_NAME, args.filename)
print("RAM boot...")
for seg in image.segments:
size = len(seg.data)
print("Downloading %d bytes at %08x..." % (size, seg.addr), end=" ")
sys.stdout.flush()
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
print("done!")
print("All segments done, executing at %08x" % image.entrypoint)
esp.mem_finish(image.entrypoint)
def read_mem(esp, args):
print("0x%08x = 0x%08x" % (args.address, esp.read_reg(args.address)))
def write_mem(esp, args):
esp.write_reg(args.address, args.value, args.mask, 0)
print("Wrote %08x, mask %08x to %08x" % (args.value, args.mask, args.address))
def dump_mem(esp, args):
with open(args.filename, "wb") as f:
for i in range(args.size // 4):
d = esp.read_reg(args.address + (i * 4))
f.write(struct.pack(b"<I", d))
if f.tell() % 1024 == 0:
print_overwrite(
"%d bytes read... (%d %%)" % (f.tell(), f.tell() * 100 // args.size)
)
sys.stdout.flush()
print_overwrite("Read %d bytes" % f.tell(), last_line=True)
print("Done!")
def detect_flash_size(esp, args=None):
# TODO: Remove the dependency on args in the next major release (v5.0)
if esp.secure_download_mode:
if args is not None and args.flash_size == "detect":
raise FatalError(
"Detecting flash size is not supported in secure download mode. "
"Need to manually specify flash size."
)
else:
return None
flash_id = esp.flash_id()
size_id = flash_id >> 16
flash_size = DETECTED_FLASH_SIZES.get(size_id)
if args is not None and args.flash_size == "detect":
if flash_size is None:
flash_size = "4MB"
print(
"Warning: Could not auto-detect Flash size "
f"(FlashID={flash_id:#x}, SizeID={size_id:#x}), defaulting to 4MB"
)
else:
print("Auto-detected Flash size:", flash_size)
args.flash_size = flash_size
return flash_size
def _update_image_flash_params(esp, address, args, image):
"""
Modify the flash mode & size bytes if this looks like an executable bootloader image
"""
if len(image) < 8:
return image # not long enough to be a bootloader image
# unpack the (potential) image header
magic, _, flash_mode, flash_size_freq = struct.unpack("BBBB", image[:4])
if address != esp.BOOTLOADER_FLASH_OFFSET:
return image # not flashing bootloader offset, so don't modify this
if (args.flash_mode, args.flash_freq, args.flash_size) == ("keep",) * 3:
return image # all settings are 'keep', not modifying anything
# easy check if this is an image: does it start with a magic byte?
if magic != esp.ESP_IMAGE_MAGIC:
print(
"Warning: Image file at 0x%x doesn't look like an image file, "
"so not changing any flash settings." % address
)
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:
print(
"Warning: Image file at 0x%x is not a valid %s image, "
"so not changing any flash settings." % (address, esp.CHIP_NAME)
)
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
# a SHA256 checksum. In that case we should not modify the header because
# the checksum check would fail.
sha_implies_keep = args.chip != "esp8266" and image[8 + 15] == 1
def print_keep_warning(arg_to_keep, arg_used):
print(
"Warning: Image file at {addr} is protected with a hash checksum, "
"so not changing the flash {arg} setting. "
"Use the --flash_{arg}=keep option instead of --flash_{arg}={arg_orig} "
"in order to remove this warning, or use the --dont-append-digest option "
"for the elf2image command in order to generate an image file "
"without a hash checksum".format(
addr=hex(address), arg=arg_to_keep, arg_orig=arg_used
)
)
if args.flash_mode != "keep":
new_flash_mode = FLASH_MODES[args.flash_mode]
if flash_mode != new_flash_mode and sha_implies_keep:
print_keep_warning("mode", args.flash_mode)
else:
flash_mode = new_flash_mode
flash_freq = flash_size_freq & 0x0F
if args.flash_freq != "keep":
new_flash_freq = esp.parse_flash_freq_arg(args.flash_freq)
if flash_freq != new_flash_freq and sha_implies_keep:
print_keep_warning("frequency", args.flash_freq)
else:
flash_freq = new_flash_freq
flash_size = flash_size_freq & 0xF0
if args.flash_size != "keep":
new_flash_size = esp.parse_flash_size_arg(args.flash_size)
if flash_size != new_flash_size and sha_implies_keep:
print_keep_warning("size", args.flash_size)
else:
flash_size = new_flash_size
flash_params = struct.pack(b"BB", flash_mode, flash_size + flash_freq)
if flash_params != image[2:4]:
print("Flash params set to 0x%04x" % struct.unpack(">H", flash_params))
image = image[0:2] + flash_params + image[4:]
return image
def write_flash(esp, args):
# set args.compress based on default behaviour:
# -> if either --compress or --no-compress is set, honour that
# -> otherwise, set --compress unless --no-stub is set
if args.compress is None and not args.no_compress:
args.compress = not args.no_stub
if not args.force and esp.CHIP_NAME != "ESP8266" and not esp.secure_download_mode:
# Check if secure boot is active
if esp.get_secure_boot_enabled():
for address, _ in args.addr_filename:
if address < 0x8000:
raise FatalError(
"Secure Boot detected, writing to flash regions < 0x8000 "
"is disabled to protect the bootloader. "
"Use --force to override, "
"please use with caution, otherwise it may brick your device!"
)
# Check if chip_id and min_rev in image are valid for the target in use
for _, argfile in args.addr_filename:
try:
image = LoadFirmwareImage(esp.CHIP_NAME, argfile)
except (FatalError, struct.error, RuntimeError):
continue
finally:
argfile.seek(0) # LoadFirmwareImage changes the file handle position
if image.chip_id != esp.IMAGE_CHIP_ID:
raise FatalError(
f"{argfile.name} is not an {esp.CHIP_NAME} image. "
"Use --force to flash anyway."
)
# this logic below decides which min_rev to use, min_rev or min/max_rev_full
if image.max_rev_full == 0: # image does not have max/min_rev_full fields
use_rev_full_fields = False
elif image.max_rev_full == 65535: # image has default value of max_rev_full
use_rev_full_fields = True
if (
image.min_rev_full == 0 and image.min_rev != 0
): # min_rev_full is not set, min_rev is used
use_rev_full_fields = False
else: # max_rev_full set to a version
use_rev_full_fields = True
if use_rev_full_fields:
rev = esp.get_chip_revision()
if rev < image.min_rev_full or rev > image.max_rev_full:
error_str = f"{argfile.name} requires chip revision in range "
error_str += (
f"[v{image.min_rev_full // 100}.{image.min_rev_full % 100} - "
)
if image.max_rev_full == 65535:
error_str += "max rev not set] "
else:
error_str += (
f"v{image.max_rev_full // 100}.{image.max_rev_full % 100}] "
)
error_str += f"(this chip is revision v{rev // 100}.{rev % 100})"
raise FatalError(f"{error_str}. Use --force to flash anyway.")
else:
# In IDF, image.min_rev is set based on Kconfig option.
# For C3 chip, image.min_rev is the Minor revision
# while for the rest chips it is the Major revision.
if esp.CHIP_NAME == "ESP32-C3":
rev = esp.get_minor_chip_version()
else:
rev = esp.get_major_chip_version()
if rev < image.min_rev:
raise FatalError(
f"{argfile.name} requires chip revision "
f"{image.min_rev} or higher (this chip is revision {rev}). "
"Use --force to flash anyway."
)
# In case we have encrypted files to write,
# we first do few sanity checks before actual flash
if args.encrypt or args.encrypt_files is not None:
do_write = True
if not esp.secure_download_mode:
if esp.get_encrypted_download_disabled():
raise FatalError(
"This chip has encrypt functionality "
"in UART download mode disabled. "
"This is the Flash Encryption configuration for Production mode "
"instead of Development mode."
)
crypt_cfg_efuse = esp.get_flash_crypt_config()
if crypt_cfg_efuse is not None and crypt_cfg_efuse != 0xF:
print("Unexpected FLASH_CRYPT_CONFIG value: 0x%x" % (crypt_cfg_efuse))
do_write = False
enc_key_valid = esp.is_flash_encryption_key_valid()
if not enc_key_valid:
print("Flash encryption key is not programmed")
do_write = False
# Determine which files list contain the ones to encrypt
files_to_encrypt = args.addr_filename if args.encrypt else args.encrypt_files
for address, argfile in files_to_encrypt:
if address % esp.FLASH_ENCRYPTED_WRITE_ALIGN:
print(
"File %s address 0x%x is not %d byte aligned, can't flash encrypted"
% (argfile.name, address, esp.FLASH_ENCRYPTED_WRITE_ALIGN)
)
do_write = False
if not do_write and not args.ignore_flash_encryption_efuse_setting:
raise FatalError(
"Can't perform encrypted flash write, "
"consult Flash Encryption documentation for more information"
)
else:
if not args.force and esp.CHIP_NAME != "ESP8266":
# ESP32 does not support `get_security_info()` and `secure_download_mode`
if (
esp.CHIP_NAME != "ESP32"
and esp.secure_download_mode
and bin(esp.get_security_info()["flash_crypt_cnt"]).count("1") & 1 != 0
):
raise FatalError(
"WARNING: Detected flash encryption and "
"secure download mode enabled.\n"
"Flashing plaintext binary may brick your device! "
"Use --force to override the warning."
)
if (
not esp.secure_download_mode
and esp.get_encrypted_download_disabled()
and esp.get_flash_encryption_enabled()
):
raise FatalError(
"WARNING: Detected flash encryption enabled and "
"download manual encrypt disabled.\n"
"Flashing plaintext binary may brick your device! "
"Use --force to override the warning."
)
# verify file sizes fit in flash
flash_end = flash_size_bytes(
detect_flash_size(esp) if args.flash_size == "keep" else args.flash_size
)
if flash_end is not None: # Not in secure download mode
for address, argfile in args.addr_filename:
argfile.seek(0, os.SEEK_END)
if address + argfile.tell() > flash_end:
raise FatalError(
"File %s (length %d) at offset %d "
"will not fit in %d bytes of flash. "
"Use --flash_size argument, or change flashing address."
% (argfile.name, argfile.tell(), address, flash_end)
)
argfile.seek(0)
if args.erase_all:
erase_flash(esp, args)
else:
for address, argfile in args.addr_filename:
argfile.seek(0, os.SEEK_END)
write_end = address + argfile.tell()
argfile.seek(0)
bytes_over = address % esp.FLASH_SECTOR_SIZE
if bytes_over != 0:
print(
"WARNING: Flash address {:#010x} is not aligned "
"to a {:#x} byte flash sector. "
"{:#x} bytes before this address will be erased.".format(
address, esp.FLASH_SECTOR_SIZE, bytes_over
)
)
# Print the address range of to-be-erased flash memory region
print(
"Flash will be erased from {:#010x} to {:#010x}...".format(
address - bytes_over,
div_roundup(write_end, esp.FLASH_SECTOR_SIZE)
* esp.FLASH_SECTOR_SIZE
- 1,
)
)
""" Create a list describing all the files we have to flash.
Each entry holds an "encrypt" flag marking whether the file needs encryption or not.
This list needs to be sorted.
First, append to each entry of our addr_filename list the flag args.encrypt
E.g., if addr_filename is [(0x1000, "partition.bin"), (0x8000, "bootloader")],
all_files will be [
(0x1000, "partition.bin", args.encrypt),
(0x8000, "bootloader", args.encrypt)
],
where, of course, args.encrypt is either True or False
"""
all_files = [
(offs, filename, args.encrypt) for (offs, filename) in args.addr_filename
]
"""
Now do the same with encrypt_files list, if defined.
In this case, the flag is True
"""
if args.encrypt_files is not None:
encrypted_files_flag = [
(offs, filename, True) for (offs, filename) in args.encrypt_files
]
# Concatenate both lists and sort them.
# As both list are already sorted, we could simply do a merge instead,
# but for the sake of simplicity and because the lists are very small,
# let's use sorted.
all_files = sorted(all_files + encrypted_files_flag, key=lambda x: x[0])
for address, argfile, encrypted in all_files:
compress = args.compress
# Check whether we can compress the current file before flashing
if compress and encrypted:
print("\nWARNING: - compress and encrypt options are mutually exclusive ")
print("Will flash %s uncompressed" % argfile.name)
compress = False
if args.no_stub:
print("Erasing flash...")
image = pad_to(
argfile.read(), esp.FLASH_ENCRYPTED_WRITE_ALIGN if encrypted else 4
)
if len(image) == 0:
print("WARNING: File %s is empty" % argfile.name)
continue
image = _update_image_flash_params(esp, address, args, image)
calcmd5 = hashlib.md5(image).hexdigest()
uncsize = len(image)
if compress:
uncimage = image
image = zlib.compress(uncimage, 9)
# Decompress the compressed binary a block at a time,
# to dynamically calculate the timeout based on the real write size
decompress = zlib.decompressobj()
blocks = esp.flash_defl_begin(uncsize, len(image), address)
else:
blocks = esp.flash_begin(uncsize, address, begin_rom_encrypted=encrypted)
argfile.seek(0) # in case we need it again
seq = 0
bytes_sent = 0 # bytes sent on wire
bytes_written = 0 # bytes written to flash
t = time.time()
timeout = DEFAULT_TIMEOUT
while len(image) > 0:
print_overwrite(
"Writing at 0x%08x... (%d %%)"
% (address + bytes_written, 100 * (seq + 1) // blocks)
)
sys.stdout.flush()
block = image[0 : esp.FLASH_WRITE_SIZE]
if compress:
# feeding each compressed block into the decompressor lets us
# see block-by-block how much will be written
block_uncompressed = len(decompress.decompress(block))
bytes_written += block_uncompressed
block_timeout = max(
DEFAULT_TIMEOUT,
timeout_per_mb(ERASE_WRITE_TIMEOUT_PER_MB, block_uncompressed),
)
if not esp.IS_STUB:
timeout = (
block_timeout # ROM code writes block to flash before ACKing
)
esp.flash_defl_block(block, seq, timeout=timeout)
if esp.IS_STUB:
# Stub ACKs when block is received,
# then writes to flash while receiving the block after it
timeout = block_timeout
else:
# Pad the last block
block = block + b"\xff" * (esp.FLASH_WRITE_SIZE - len(block))
if encrypted:
esp.flash_encrypt_block(block, seq)
else:
esp.flash_block(block, seq)
bytes_written += len(block)
bytes_sent += len(block)
image = image[esp.FLASH_WRITE_SIZE :]
seq += 1
if esp.IS_STUB:
# Stub only writes each block to flash after 'ack'ing the receive,
# so do a final dummy operation which will not be 'ack'ed
# until the last block has actually been written out to flash
esp.read_reg(ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR, timeout=timeout)
t = time.time() - t
speed_msg = ""
if compress:
if t > 0.0:
speed_msg = " (effective %.1f kbit/s)" % (uncsize / t * 8 / 1000)
print_overwrite(
"Wrote %d bytes (%d compressed) at 0x%08x in %.1f seconds%s..."
% (uncsize, bytes_sent, address, t, speed_msg),
last_line=True,
)
else:
if t > 0.0:
speed_msg = " (%.1f kbit/s)" % (bytes_written / t * 8 / 1000)
print_overwrite(
"Wrote %d bytes at 0x%08x in %.1f seconds%s..."
% (bytes_written, address, t, speed_msg),
last_line=True,
)
if not encrypted and not esp.secure_download_mode:
try:
res = esp.flash_md5sum(address, uncsize)
if res != calcmd5:
print("File md5: %s" % calcmd5)
print("Flash md5: %s" % res)
print(
"MD5 of 0xFF is %s"
% (hashlib.md5(b"\xFF" * uncsize).hexdigest())
)
raise FatalError("MD5 of file does not match data in flash!")
else:
print("Hash of data verified.")
except NotImplementedInROMError:
pass
print("\nLeaving...")
if esp.IS_STUB:
# skip sending flash_finish to ROM loader here,
# as it causes the loader to exit and run user code
esp.flash_begin(0, 0)
# Get the "encrypted" flag for the last file flashed
# Note: all_files list contains triplets like:
# (address: Integer, filename: String, encrypted: Boolean)
last_file_encrypted = all_files[-1][2]
# Check whether the last file flashed was compressed or not
if args.compress and not last_file_encrypted:
esp.flash_defl_finish(False)
else:
esp.flash_finish(False)
if args.verify:
print("Verifying just-written flash...")
print(
"(This option is deprecated, "
"flash contents are now always read back after flashing.)"
)
# If some encrypted files have been flashed,
# print a warning saying that we won't check them
if args.encrypt or args.encrypt_files is not None:
print("WARNING: - cannot verify encrypted files, they will be ignored")
# Call verify_flash function only if there is at least
# one non-encrypted file flashed
if not args.encrypt:
verify_flash(esp, args)
def image_info(args):
def v2():
def get_key_from_value(dict, val):
"""Get key from value in dictionary"""
for key, value in dict.items():
if value == val:
return key
return None
print()
title = "{} image header".format(args.chip.upper())
print(title)
print("=" * len(title))
print("Image version: {}".format(image.version))
print(
"Entry point: {:#8x}".format(image.entrypoint)
if image.entrypoint != 0
else "Entry point not set"
)
print("Segments: {}".format(len(image.segments)))
# Flash size
flash_s_bits = image.flash_size_freq & 0xF0 # high four bits
flash_s = get_key_from_value(image.ROM_LOADER.FLASH_SIZES, flash_s_bits)
print(
"Flash size: {}".format(flash_s)
if flash_s is not None
else "WARNING: Invalid flash size ({:#02x})".format(flash_s_bits)
)
# Flash frequency
flash_fr_bits = image.flash_size_freq & 0x0F # low four bits
flash_fr = get_key_from_value(image.ROM_LOADER.FLASH_FREQUENCY, flash_fr_bits)
print(
"Flash freq: {}".format(flash_fr)
if flash_fr is not None
else "WARNING: Invalid flash frequency ({:#02x})".format(flash_fr_bits)
)
# Flash mode
flash_mode = get_key_from_value(FLASH_MODES, image.flash_mode)
print(
"Flash mode: {}".format(flash_mode.upper())
if flash_mode is not None
else "WARNING: Invalid flash mode ({})".format(image.flash_mode)
)
# Extended header (ESP32 and later only)
if args.chip != "esp8266":
print()
title = "{} extended image header".format(args.chip.upper())
print(title)
print("=" * len(title))
print(
f"WP pin: {image.wp_pin:#02x}",
*["(disabled)"] if image.wp_pin == image.WP_PIN_DISABLED else [],
)
print(
"Flash pins drive settings: "
"clk_drv: {:#02x}, q_drv: {:#02x}, d_drv: {:#02x}, "
"cs0_drv: {:#02x}, hd_drv: {:#02x}, wp_drv: {:#02x}".format(
image.clk_drv,
image.q_drv,
image.d_drv,
image.cs_drv,
image.hd_drv,
image.wp_drv,
)
)
try:
chip = next(
chip
for chip in CHIP_DEFS.values()
if getattr(chip, "IMAGE_CHIP_ID", None) == image.chip_id
)
print(f"Chip ID: {image.chip_id} ({chip.CHIP_NAME})")
except StopIteration:
print(f"Chip ID: {image.chip_id} (Unknown ID)")
print(
"Minimal chip revision: "
f"v{image.min_rev_full // 100}.{image.min_rev_full % 100}, "
f"(legacy min_rev = {image.min_rev})"
)
print(
"Maximal chip revision: "
f"v{image.max_rev_full // 100}.{image.max_rev_full % 100}"
)
print()
# Segments overview
title = "Segments information"
print(title)
print("=" * len(title))
headers_str = "{:>7} {:>7} {:>10} {:>10} {:10}"
print(
headers_str.format(
"Segment", "Length", "Load addr", "File offs", "Memory types"
)
)
print(
"{} {} {} {} {}".format("-" * 7, "-" * 7, "-" * 10, "-" * 10, "-" * 12)
)
format_str = "{:7} {:#07x} {:#010x} {:#010x} {}"
app_desc = None
bootloader_desc = None
for idx, seg in enumerate(image.segments, start=1):
segs = seg.get_memory_type(image)
seg_name = ", ".join(segs)
if "DROM" in segs: # The DROM segment starts with the esp_app_desc_t struct
app_desc = seg.data[:256]
elif "DRAM" in segs:
# The DRAM segment starts with the esp_bootloader_desc_t struct
if len(seg.data) >= 80:
bootloader_desc = seg.data[:80]
print(
format_str.format(idx, len(seg.data), seg.addr, seg.file_offs, seg_name)
)
print()
# Footer
title = f"{args.chip.upper()} image footer"
print(title)
print("=" * len(title))
calc_checksum = image.calculate_checksum()
print(
"Checksum: {:#02x} ({})".format(
image.checksum,
"valid"
if image.checksum == calc_checksum
else "invalid - calculated {:02x}".format(calc_checksum),
)
)
try:
digest_msg = "Not appended"
if image.append_digest:
is_valid = image.stored_digest == image.calc_digest
digest_msg = "{} ({})".format(
hexify(image.calc_digest, uppercase=False),
"valid" if is_valid else "invalid",
)
print("Validation hash: {}".format(digest_msg))
except AttributeError:
pass # ESP8266 image has no append_digest field
if app_desc:
APP_DESC_STRUCT_FMT = "<II" + "8s" + "32s32s16s16s32s32s" + "80s"
(
magic_word,
secure_version,
reserv1,
version,
project_name,
time,
date,
idf_ver,
app_elf_sha256,
reserv2,
) = struct.unpack(APP_DESC_STRUCT_FMT, app_desc)
if magic_word == 0xABCD5432:
print()
title = "Application information"
print(title)
print("=" * len(title))
print(f'Project name: {project_name.decode("utf-8")}')
print(f'App version: {version.decode("utf-8")}')
print(f'Compile time: {date.decode("utf-8")} {time.decode("utf-8")}')
print(f"ELF file SHA256: {hexify(app_elf_sha256, uppercase=False)}")
print(f'ESP-IDF: {idf_ver.decode("utf-8")}')
print(f"Secure version: {secure_version}")
elif bootloader_desc:
BOOTLOADER_DESC_STRUCT_FMT = "<B" + "3s" + "I32s24s" + "16s"
(
magic_byte,
reserved,
version,
idf_ver,
date_time,
reserved2,
) = struct.unpack(BOOTLOADER_DESC_STRUCT_FMT, bootloader_desc)
if magic_byte == 80:
print()
title = "Bootloader information"
print(title)
print("=" * len(title))
print(f"Bootloader version: {version}")
print(f'ESP-IDF: {idf_ver.decode("utf-8")}')
print(f'Compile time: {date_time.decode("utf-8")}')
print(f"File size: {get_file_size(args.filename)} (bytes)")
with open(args.filename, "rb") as f:
# magic number
try:
common_header = f.read(8)
magic = common_header[0]
except IndexError:
raise FatalError("File is empty")
if magic not in [
ESPLoader.ESP_IMAGE_MAGIC,
ESP8266V2FirmwareImage.IMAGE_V2_MAGIC,
]:
raise FatalError(
"This is not a valid image "
"(invalid magic number: {:#x})".format(magic)
)
if args.chip == "auto":
try:
extended_header = f.read(16)
# append_digest, either 0 or 1
if extended_header[-1] not in [0, 1]:
raise FatalError("Append digest field not 0 or 1")
chip_id = int.from_bytes(extended_header[4:5], "little")
for rom in [n for n in ROM_LIST if n.CHIP_NAME != "ESP8266"]:
if chip_id == rom.IMAGE_CHIP_ID:
args.chip = rom.CHIP_NAME
break
else:
raise FatalError(f"Unknown image chip ID ({chip_id})")
except FatalError:
args.chip = "esp8266"
print(f"Detected image type: {args.chip.upper()}")
image = LoadFirmwareImage(args.chip, args.filename)
if args.version == "2":
v2()
return
print("Image version: {}".format(image.version))
print(
"Entry point: {:8x}".format(image.entrypoint)
if image.entrypoint != 0
else "Entry point not set"
)
print("{} segments".format(len(image.segments)))
print()
idx = 0
for seg in image.segments:
idx += 1
segs = seg.get_memory_type(image)
seg_name = ",".join(segs)
print("Segment {}: {} [{}]".format(idx, seg, seg_name))
calc_checksum = image.calculate_checksum()
print(
"Checksum: {:02x} ({})".format(
image.checksum,
"valid"
if image.checksum == calc_checksum
else "invalid - calculated {:02x}".format(calc_checksum),
)
)
try:
digest_msg = "Not appended"
if image.append_digest:
is_valid = image.stored_digest == image.calc_digest
digest_msg = "{} ({})".format(
hexify(image.calc_digest, uppercase=False),
"valid" if is_valid else "invalid",
)
print("Validation Hash: {}".format(digest_msg))
except AttributeError:
pass # ESP8266 image has no append_digest field
def make_image(args):
print("Creating {} image...".format(args.chip))
image = ESP8266ROMFirmwareImage()
if len(args.segfile) == 0:
raise FatalError("No segments specified")
if len(args.segfile) != len(args.segaddr):
raise FatalError(
"Number of specified files does not match number of specified addresses"
)
for seg, addr in zip(args.segfile, args.segaddr):
with open(seg, "rb") as f:
data = f.read()
image.segments.append(ImageSegment(addr, data))
image.entrypoint = args.entrypoint
image.save(args.output)
print("Successfully created {} image.".format(args.chip))
def elf2image(args):
e = ELFFile(args.input)
if args.chip == "auto": # Default to ESP8266 for backwards compatibility
args.chip = "esp8266"
print("Creating {} image...".format(args.chip))
if args.chip != "esp8266":
image = CHIP_DEFS[args.chip].BOOTLOADER_IMAGE()
if args.chip == "esp32" and args.secure_pad:
image.secure_pad = "1"
if args.secure_pad_v2:
image.secure_pad = "2"
image.min_rev = args.min_rev
image.min_rev_full = args.min_rev_full
image.max_rev_full = args.max_rev_full
image.append_digest = args.append_digest
elif args.version == "1": # ESP8266
image = ESP8266ROMFirmwareImage()
elif args.version == "2":
image = ESP8266V2FirmwareImage()
else:
image = ESP8266V3FirmwareImage()
image.entrypoint = e.entrypoint
image.flash_mode = FLASH_MODES[args.flash_mode]
if args.flash_mmu_page_size:
image.set_mmu_page_size(flash_size_bytes(args.flash_mmu_page_size))
# ELFSection is a subclass of ImageSegment, so can use interchangeably
image.segments = e.segments if args.use_segments else e.sections
if args.pad_to_size:
image.pad_to_size = flash_size_bytes(args.pad_to_size)
image.flash_size_freq = image.ROM_LOADER.parse_flash_size_arg(args.flash_size)
image.flash_size_freq += image.ROM_LOADER.parse_flash_freq_arg(args.flash_freq)
if args.elf_sha256_offset:
image.elf_sha256 = e.sha256()
image.elf_sha256_offset = args.elf_sha256_offset
before = len(image.segments)
image.merge_adjacent_segments()
if len(image.segments) != before:
delta = before - len(image.segments)
print("Merged %d ELF section%s" % (delta, "s" if delta > 1 else ""))
image.verify()
if args.output is None:
args.output = image.default_output_name(args.input)
image.save(args.output)
print("Successfully created {} image.".format(args.chip))
def read_mac(esp, args):
def print_mac(label, mac):
print("%s: %s" % (label, ":".join(map(lambda x: "%02x" % x, mac))))
eui64 = esp.read_mac("EUI64")
if eui64:
print_mac("MAC", eui64)
print_mac("BASE MAC", esp.read_mac("BASE_MAC"))
print_mac("MAC_EXT", esp.read_mac("MAC_EXT"))
else:
print_mac("MAC", esp.read_mac("BASE_MAC"))
def chip_id(esp, args):
try:
chipid = esp.chip_id()
print("Chip ID: 0x%08x" % chipid)
except NotSupportedError:
print("Warning: %s has no Chip ID. Reading MAC instead." % esp.CHIP_NAME)
read_mac(esp, args)
def erase_flash(esp, args):
if not args.force and esp.CHIP_NAME != "ESP8266" and not esp.secure_download_mode:
if esp.get_flash_encryption_enabled() or esp.get_secure_boot_enabled():
raise FatalError(
"Active security features detected, "
"erasing flash is disabled as a safety measure. "
"Use --force to override, "
"please use with caution, otherwise it may brick your device!"
)
print("Erasing flash (this may take a while)...")
t = time.time()
esp.erase_flash()
print("Chip erase completed successfully in %.1fs" % (time.time() - t))
def erase_region(esp, args):
if not args.force and esp.CHIP_NAME != "ESP8266" and not esp.secure_download_mode:
if esp.get_flash_encryption_enabled() or esp.get_secure_boot_enabled():
raise FatalError(
"Active security features detected, "
"erasing flash is disabled as a safety measure. "
"Use --force to override, "
"please use with caution, otherwise it may brick your device!"
)
print("Erasing region (may be slow depending on size)...")
t = time.time()
esp.erase_region(args.address, args.size)
print("Erase completed successfully in %.1f seconds." % (time.time() - t))
def run(esp, args):
esp.run()
def flash_id(esp, args):
flash_id = esp.flash_id()
print("Manufacturer: %02x" % (flash_id & 0xFF))
flid_lowbyte = (flash_id >> 16) & 0xFF
print("Device: %02x%02x" % ((flash_id >> 8) & 0xFF, flid_lowbyte))
print(
"Detected flash size: %s" % (DETECTED_FLASH_SIZES.get(flid_lowbyte, "Unknown"))
)
flash_type = esp.flash_type()
flash_type_dict = {0: "quad (4 data lines)", 1: "octal (8 data lines)"}
flash_type_str = flash_type_dict.get(flash_type)
if flash_type_str:
print(f"Flash type set in eFuse: {flash_type_str}")
def read_flash(esp, args):
if args.no_progress:
flash_progress = None
else:
def flash_progress(progress, length):
msg = "%d (%d %%)" % (progress, progress * 100.0 / length)
padding = "\b" * len(msg)
if progress == length:
padding = "\n"
sys.stdout.write(msg + padding)
sys.stdout.flush()
t = time.time()
data = esp.read_flash(args.address, args.size, flash_progress)
t = time.time() - t
speed_msg = " ({:.1f} kbit/s)".format(len(data) / t * 8 / 1000) if t > 0.0 else ""
print_overwrite(
"Read {:d} bytes at {:#010x} in {:.1f} seconds{}...".format(
len(data), args.address, t, speed_msg
),
last_line=True,
)
with open(args.filename, "wb") as f:
f.write(data)
def verify_flash(esp, args):
differences = False
for address, argfile in args.addr_filename:
image = pad_to(argfile.read(), 4)
argfile.seek(0) # rewind in case we need it again
image = _update_image_flash_params(esp, address, args, image)
image_size = len(image)
print(
"Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s..."
% (image_size, image_size, address, argfile.name)
)
# Try digest first, only read if there are differences.
digest = esp.flash_md5sum(address, image_size)
expected_digest = hashlib.md5(image).hexdigest()
if digest == expected_digest:
print("-- verify OK (digest matched)")
continue
else:
differences = True
if getattr(args, "diff", "no") != "yes":
print("-- verify FAILED (digest mismatch)")
continue
flash = esp.read_flash(address, image_size)
assert flash != image
diff = [i for i in range(image_size) if flash[i] != image[i]]
print(
"-- verify FAILED: %d differences, first @ 0x%08x"
% (len(diff), address + diff[0])
)
for d in diff:
flash_byte = flash[d]
image_byte = image[d]
print(" %08x %02x %02x" % (address + d, flash_byte, image_byte))
if differences:
raise FatalError("Verify failed.")
def read_flash_status(esp, args):
print("Status value: 0x%04x" % esp.read_status(args.bytes))
def write_flash_status(esp, args):
fmt = "0x%%0%dx" % (args.bytes * 2)
args.value = args.value & ((1 << (args.bytes * 8)) - 1)
print(("Initial flash status: " + fmt) % esp.read_status(args.bytes))
print(("Setting flash status: " + fmt) % args.value)
esp.write_status(args.value, args.bytes, args.non_volatile)
print(("After flash status: " + fmt) % esp.read_status(args.bytes))
# The following mapping was taken from the ROM code
# This mapping is same across all targets in the ROM
SECURITY_INFO_FLAG_MAP = {
"SECURE_BOOT_EN": (1 << 0),
"SECURE_BOOT_AGGRESSIVE_REVOKE": (1 << 1),
"SECURE_DOWNLOAD_ENABLE": (1 << 2),
"SECURE_BOOT_KEY_REVOKE0": (1 << 3),
"SECURE_BOOT_KEY_REVOKE1": (1 << 4),
"SECURE_BOOT_KEY_REVOKE2": (1 << 5),
"SOFT_DIS_JTAG": (1 << 6),
"HARD_DIS_JTAG": (1 << 7),
"DIS_USB": (1 << 8),
"DIS_DOWNLOAD_DCACHE": (1 << 9),
"DIS_DOWNLOAD_ICACHE": (1 << 10),
}
# Get the status of respective security flag
def get_security_flag_status(flag_name, flags_value):
try:
return (flags_value & SECURITY_INFO_FLAG_MAP[flag_name]) != 0
except KeyError:
raise ValueError(f"Invalid flag name: {flag_name}")
def get_security_info(esp, args):
si = esp.get_security_info()
print()
title = "Security Information:"
print(title)
print("=" * len(title))
print("Flags: {:#010x} ({})".format(si["flags"], bin(si["flags"])))
print("Key Purposes: {}".format(si["key_purposes"]))
if si["chip_id"] is not None and si["api_version"] is not None:
print("Chip ID: {}".format(si["chip_id"]))
print("API Version: {}".format(si["api_version"]))
flags = si["flags"]
if get_security_flag_status("SECURE_BOOT_EN", flags):
print("Secure Boot: Enabled")
if get_security_flag_status("SECURE_BOOT_AGGRESSIVE_REVOKE", flags):
print("Secure Boot Aggressive key revocation: Enabled")
revoked_keys = []
for i, key in enumerate(
[
"SECURE_BOOT_KEY_REVOKE0",
"SECURE_BOOT_KEY_REVOKE1",
"SECURE_BOOT_KEY_REVOKE2",
]
):
if get_security_flag_status(key, flags):
revoked_keys.append(i)
if len(revoked_keys) > 0:
print("Secure Boot Key Revocation Status:\n")
for i in revoked_keys:
print(f"\tSecure Boot Key{i} is Revoked\n")
else:
print("Secure Boot: Disabled")
flash_crypt_cnt = bin(si["flash_crypt_cnt"])
if (flash_crypt_cnt.count("1") % 2) != 0:
print("Flash Encryption: Enabled")
else:
print("Flash Encryption: Disabled")
CRYPT_CNT_STRING = "SPI Boot Crypt Count (SPI_BOOT_CRYPT_CNT)"
if esp.CHIP_NAME == "esp32":
CRYPT_CNT_STRING = "Flash Crypt Count (FLASH_CRYPT_CNT)"
print(f"{CRYPT_CNT_STRING}: {si['flash_crypt_cnt']:#x}")
if get_security_flag_status("DIS_DOWNLOAD_DCACHE", flags):
print("Dcache in UART download mode: Disabled")
if get_security_flag_status("DIS_DOWNLOAD_ICACHE", flags):
print("Icache in UART download mode: Disabled")
hard_dis_jtag = get_security_flag_status("HARD_DIS_JTAG", flags)
soft_dis_jtag = get_security_flag_status("SOFT_DIS_JTAG", flags)
if hard_dis_jtag:
print("JTAG: Permenantly Disabled")
elif soft_dis_jtag:
print("JTAG: Software Access Disabled")
if get_security_flag_status("DIS_USB", flags):
print("USB Access: Disabled")
def merge_bin(args):
try:
chip_class = CHIP_DEFS[args.chip]
except KeyError:
msg = (
"Please specify the chip argument"
if args.chip == "auto"
else "Invalid chip choice: '{}'".format(args.chip)
)
msg = msg + " (choose from {})".format(", ".join(CHIP_LIST))
raise FatalError(msg)
# sort the files by offset.
# The AddrFilenamePairAction has already checked for overlap
input_files = sorted(args.addr_filename, key=lambda x: x[0])
if not input_files:
raise FatalError("No input files specified")
first_addr = input_files[0][0]
if first_addr < args.target_offset:
raise FatalError(
"Output file target offset is 0x%x. Input file offset 0x%x is before this."
% (args.target_offset, first_addr)
)
if args.format != "raw":
raise FatalError(
"This version of esptool only supports the 'raw' output format"
)
with open(args.output, "wb") as of:
def pad_to(flash_offs):
# account for output file offset if there is any
of.write(b"\xFF" * (flash_offs - args.target_offset - of.tell()))
for addr, argfile in input_files:
pad_to(addr)
image = argfile.read()
image = _update_image_flash_params(chip_class, addr, args, image)
of.write(image)
if args.fill_flash_size:
pad_to(flash_size_bytes(args.fill_flash_size))
print(
"Wrote 0x%x bytes to file %s, ready to flash to offset 0x%x"
% (of.tell(), args.output, args.target_offset)
)
def version(args):
from . import __version__
print(__version__)
| 49,873 | Python | .py | 1,166 | 31.801029 | 88 | 0.563813 | OLIMEX/RVPC | 8 | 2 | 1 | GPL-3.0 | 9/5/2024, 10:48:43 PM (Europe/Amsterdam) |
2,289,604 | bin_image.py | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/bin_image.py | # SPDX-FileCopyrightText: 2014-2022 Fredrik Ahlberg, Angus Gratton,
# Espressif Systems (Shanghai) CO LTD, other contributors as noted.
#
# SPDX-License-Identifier: GPL-2.0-or-later
import binascii
import copy
import hashlib
import io
import os
import re
import struct
from .loader import ESPLoader
from .targets import (
ESP32C2ROM,
ESP32C3ROM,
ESP32C6BETAROM,
ESP32C6ROM,
ESP32H2BETA1ROM,
ESP32H2BETA2ROM,
ESP32H2ROM,
ESP32ROM,
ESP32S2ROM,
ESP32S3BETA2ROM,
ESP32S3ROM,
ESP8266ROM,
)
from .util import FatalError, byte, pad_to
def align_file_position(f, size):
"""Align the position in the file to the next block of specified size"""
align = (size - 1) - (f.tell() % size)
f.seek(align, 1)
def LoadFirmwareImage(chip, image_file):
"""
Load a firmware image. Can be for any supported SoC.
ESP8266 images will be examined to determine if they are original ROM firmware
images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1)
or ESP8266V2FirmwareImage (v2).
"""
def select_image_class(f, chip):
chip = re.sub(r"[-()]", "", chip.lower())
if chip != "esp8266":
return {
"esp32": ESP32FirmwareImage,
"esp32s2": ESP32S2FirmwareImage,
"esp32s3beta2": ESP32S3BETA2FirmwareImage,
"esp32s3": ESP32S3FirmwareImage,
"esp32c3": ESP32C3FirmwareImage,
"esp32c6beta": ESP32C6BETAFirmwareImage,
"esp32h2beta1": ESP32H2BETA1FirmwareImage,
"esp32h2beta2": ESP32H2BETA2FirmwareImage,
"esp32c2": ESP32C2FirmwareImage,
"esp32c6": ESP32C6FirmwareImage,
"esp32h2": ESP32H2FirmwareImage,
}[chip](f)
else: # Otherwise, ESP8266 so look at magic to determine the image type
magic = ord(f.read(1))
f.seek(0)
if magic == ESPLoader.ESP_IMAGE_MAGIC:
return ESP8266ROMFirmwareImage(f)
elif magic == ESP8266V2FirmwareImage.IMAGE_V2_MAGIC:
return ESP8266V2FirmwareImage(f)
else:
raise FatalError("Invalid image magic number: %d" % magic)
if isinstance(image_file, str):
with open(image_file, "rb") as f:
return select_image_class(f, chip)
return select_image_class(image_file, chip)
class ImageSegment(object):
"""Wrapper class for a segment in an ESP image
(very similar to a section in an ELFImage also)"""
def __init__(self, addr, data, file_offs=None):
self.addr = addr
self.data = data
self.file_offs = file_offs
self.include_in_checksum = True
if self.addr != 0:
self.pad_to_alignment(
4
) # pad all "real" ImageSegments 4 byte aligned length
def copy_with_new_addr(self, new_addr):
"""Return a new ImageSegment with same data, but mapped at
a new address."""
return ImageSegment(new_addr, self.data, 0)
def split_image(self, split_len):
"""Return a new ImageSegment which splits "split_len" bytes
from the beginning of the data. Remaining bytes are kept in
this segment object (and the start address is adjusted to match.)"""
result = copy.copy(self)
result.data = self.data[:split_len]
self.data = self.data[split_len:]
self.addr += split_len
self.file_offs = None
result.file_offs = None
return result
def __repr__(self):
r = "len 0x%05x load 0x%08x" % (len(self.data), self.addr)
if self.file_offs is not None:
r += " file_offs 0x%08x" % (self.file_offs)
return r
def get_memory_type(self, image):
"""
Return a list describing the memory type(s) that is covered by this
segment's start address.
"""
return [
map_range[2]
for map_range in image.ROM_LOADER.MEMORY_MAP
if map_range[0] <= self.addr < map_range[1]
]
def pad_to_alignment(self, alignment):
self.data = pad_to(self.data, alignment, b"\x00")
class ELFSection(ImageSegment):
"""Wrapper class for a section in an ELF image, has a section
name as well as the common properties of an ImageSegment."""
def __init__(self, name, addr, data):
super(ELFSection, self).__init__(addr, data)
self.name = name.decode("utf-8")
def __repr__(self):
return "%s %s" % (self.name, super(ELFSection, self).__repr__())
class BaseFirmwareImage(object):
SEG_HEADER_LEN = 8
SHA256_DIGEST_LEN = 32
""" Base class with common firmware image functions """
def __init__(self):
self.segments = []
self.entrypoint = 0
self.elf_sha256 = None
self.elf_sha256_offset = 0
self.pad_to_size = 0
def load_common_header(self, load_file, expected_magic):
(
magic,
segments,
self.flash_mode,
self.flash_size_freq,
self.entrypoint,
) = struct.unpack("<BBBBI", load_file.read(8))
if magic != expected_magic:
raise FatalError("Invalid firmware image magic=0x%x" % (magic))
return segments
def verify(self):
if len(self.segments) > 16:
raise FatalError(
"Invalid segment count %d (max 16). "
"Usually this indicates a linker script problem." % len(self.segments)
)
def load_segment(self, f, is_irom_segment=False):
"""Load the next segment from the image file"""
file_offs = f.tell()
(offset, size) = struct.unpack("<II", f.read(8))
self.warn_if_unusual_segment(offset, size, is_irom_segment)
segment_data = f.read(size)
if len(segment_data) < size:
raise FatalError(
"End of file reading segment 0x%x, length %d (actual length %d)"
% (offset, size, len(segment_data))
)
segment = ImageSegment(offset, segment_data, file_offs)
self.segments.append(segment)
return segment
def warn_if_unusual_segment(self, offset, size, is_irom_segment):
if not is_irom_segment:
if offset > 0x40200000 or offset < 0x3FFE0000 or size > 65536:
print("WARNING: Suspicious segment 0x%x, length %d" % (offset, size))
def maybe_patch_segment_data(self, f, segment_data):
"""
If SHA256 digest of the ELF file needs to be inserted into this segment, do so.
Returns segment data.
"""
segment_len = len(segment_data)
file_pos = f.tell() # file_pos is position in the .bin file
if (
self.elf_sha256_offset >= file_pos
and self.elf_sha256_offset < file_pos + segment_len
):
# SHA256 digest needs to be patched into this binary segment,
# calculate offset of the digest inside the binary segment.
patch_offset = self.elf_sha256_offset - file_pos
# Sanity checks
if (
patch_offset < self.SEG_HEADER_LEN
or patch_offset + self.SHA256_DIGEST_LEN > segment_len
):
raise FatalError(
"Cannot place SHA256 digest on segment boundary"
"(elf_sha256_offset=%d, file_pos=%d, segment_size=%d)"
% (self.elf_sha256_offset, file_pos, segment_len)
)
# offset relative to the data part
patch_offset -= self.SEG_HEADER_LEN
if (
segment_data[patch_offset : patch_offset + self.SHA256_DIGEST_LEN]
!= b"\x00" * self.SHA256_DIGEST_LEN
):
raise FatalError(
"Contents of segment at SHA256 digest offset 0x%x are not all zero."
" Refusing to overwrite." % self.elf_sha256_offset
)
assert len(self.elf_sha256) == self.SHA256_DIGEST_LEN
segment_data = (
segment_data[0:patch_offset]
+ self.elf_sha256
+ segment_data[patch_offset + self.SHA256_DIGEST_LEN :]
)
return segment_data
def save_segment(self, f, segment, checksum=None):
"""
Save the next segment to the image file,
return next checksum value if provided
"""
segment_data = self.maybe_patch_segment_data(f, segment.data)
f.write(struct.pack("<II", segment.addr, len(segment_data)))
f.write(segment_data)
if checksum is not None:
return ESPLoader.checksum(segment_data, checksum)
def save_flash_segment(self, f, segment, checksum=None):
"""
Save the next segment to the image file, return next checksum value if provided
"""
if self.ROM_LOADER.CHIP_NAME == "ESP32":
# Work around a bug in ESP-IDF 2nd stage bootloader, that it didn't map the
# last MMU page, if an IROM/DROM segment was < 0x24 bytes
# over the page boundary.
segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN
segment_len_remainder = segment_end_pos % self.IROM_ALIGN
if segment_len_remainder < 0x24:
segment.data += b"\x00" * (0x24 - segment_len_remainder)
return self.save_segment(f, segment, checksum)
def read_checksum(self, f):
"""Return ESPLoader checksum from end of just-read image"""
# Skip the padding. The checksum is stored in the last byte so that the
# file is a multiple of 16 bytes.
align_file_position(f, 16)
return ord(f.read(1))
def calculate_checksum(self):
"""
Calculate checksum of loaded image, based on segments in
segment array.
"""
checksum = ESPLoader.ESP_CHECKSUM_MAGIC
for seg in self.segments:
if seg.include_in_checksum:
checksum = ESPLoader.checksum(seg.data, checksum)
return checksum
def append_checksum(self, f, checksum):
"""Append ESPLoader checksum to the just-written image"""
align_file_position(f, 16)
f.write(struct.pack(b"B", checksum))
def write_common_header(self, f, segments):
f.write(
struct.pack(
"<BBBBI",
ESPLoader.ESP_IMAGE_MAGIC,
len(segments),
self.flash_mode,
self.flash_size_freq,
self.entrypoint,
)
)
def is_irom_addr(self, addr):
"""
Returns True if an address starts in the irom region.
Valid for ESP8266 only.
"""
return ESP8266ROM.IROM_MAP_START <= addr < ESP8266ROM.IROM_MAP_END
def get_irom_segment(self):
irom_segments = [s for s in self.segments if self.is_irom_addr(s.addr)]
if len(irom_segments) > 0:
if len(irom_segments) != 1:
raise FatalError(
"Found %d segments that could be irom0. Bad ELF file?"
% len(irom_segments)
)
return irom_segments[0]
return None
def get_non_irom_segments(self):
irom_segment = self.get_irom_segment()
return [s for s in self.segments if s != irom_segment]
def merge_adjacent_segments(self):
if not self.segments:
return # nothing to merge
segments = []
# The easiest way to merge the sections is the browse them backward.
for i in range(len(self.segments) - 1, 0, -1):
# elem is the previous section, the one `next_elem` may need to be
# merged in
elem = self.segments[i - 1]
next_elem = self.segments[i]
if all(
(
elem.get_memory_type(self) == next_elem.get_memory_type(self),
elem.include_in_checksum == next_elem.include_in_checksum,
next_elem.addr == elem.addr + len(elem.data),
)
):
# Merge any segment that ends where the next one starts,
# without spanning memory types
#
# (don't 'pad' any gaps here as they may be excluded from the image
# due to 'noinit' or other reasons.)
elem.data += next_elem.data
else:
# The section next_elem cannot be merged into the previous one,
# which means it needs to be part of the final segments.
# As we are browsing the list backward, the elements need to be
# inserted at the beginning of the final list.
segments.insert(0, next_elem)
# The first segment will always be here as it cannot be merged into any
# "previous" section.
segments.insert(0, self.segments[0])
# note: we could sort segments here as well, but the ordering of segments is
# sometimes important for other reasons (like embedded ELF SHA-256),
# so we assume that the linker script will have produced any adjacent sections
# in linear order in the ELF, anyhow.
self.segments = segments
def set_mmu_page_size(self, size):
"""
If supported, this should be overridden by the chip-specific class.
Gets called in elf2image.
"""
print(
"WARNING: Changing MMU page size is not supported on {}! "
"Defaulting to 64KB.".format(self.ROM_LOADER.CHIP_NAME)
)
class ESP8266ROMFirmwareImage(BaseFirmwareImage):
"""'Version 1' firmware image, segments loaded directly by the ROM bootloader."""
ROM_LOADER = ESP8266ROM
def __init__(self, load_file=None):
super(ESP8266ROMFirmwareImage, self).__init__()
self.flash_mode = 0
self.flash_size_freq = 0
self.version = 1
if load_file is not None:
segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
for _ in range(segments):
self.load_segment(load_file)
self.checksum = self.read_checksum(load_file)
self.verify()
def default_output_name(self, input_file):
"""Derive a default output name from the ELF name."""
return input_file + "-"
def save(self, basename):
"""Save a set of V1 images for flashing. Parameter is a base filename."""
# IROM data goes in its own plain binary file
irom_segment = self.get_irom_segment()
if irom_segment is not None:
with open(
"%s0x%05x.bin"
% (basename, irom_segment.addr - ESP8266ROM.IROM_MAP_START),
"wb",
) as f:
f.write(irom_segment.data)
# everything but IROM goes at 0x00000 in an image file
normal_segments = self.get_non_irom_segments()
with open("%s0x00000.bin" % basename, "wb") as f:
self.write_common_header(f, normal_segments)
checksum = ESPLoader.ESP_CHECKSUM_MAGIC
for segment in normal_segments:
checksum = self.save_segment(f, segment, checksum)
self.append_checksum(f, checksum)
ESP8266ROM.BOOTLOADER_IMAGE = ESP8266ROMFirmwareImage
class ESP8266V2FirmwareImage(BaseFirmwareImage):
"""'Version 2' firmware image, segments loaded by software bootloader stub
(ie Espressif bootloader or rboot)
"""
ROM_LOADER = ESP8266ROM
# First byte of the "v2" application image
IMAGE_V2_MAGIC = 0xEA
# First 'segment' value in a "v2" application image,
# appears to be a constant version value?
IMAGE_V2_SEGMENT = 4
def __init__(self, load_file=None):
super(ESP8266V2FirmwareImage, self).__init__()
self.version = 2
if load_file is not None:
segments = self.load_common_header(load_file, self.IMAGE_V2_MAGIC)
if segments != self.IMAGE_V2_SEGMENT:
# segment count is not really segment count here,
# but we expect to see '4'
print(
'Warning: V2 header has unexpected "segment" count %d (usually 4)'
% segments
)
# irom segment comes before the second header
#
# the file is saved in the image with a zero load address
# in the header, so we need to calculate a load address
irom_segment = self.load_segment(load_file, True)
# for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_addr + 8
irom_segment.addr = 0
irom_segment.include_in_checksum = False
first_flash_mode = self.flash_mode
first_flash_size_freq = self.flash_size_freq
first_entrypoint = self.entrypoint
# load the second header
segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
if first_flash_mode != self.flash_mode:
print(
"WARNING: Flash mode value in first header (0x%02x) disagrees "
"with second (0x%02x). Using second value."
% (first_flash_mode, self.flash_mode)
)
if first_flash_size_freq != self.flash_size_freq:
print(
"WARNING: Flash size/freq value in first header (0x%02x) disagrees "
"with second (0x%02x). Using second value."
% (first_flash_size_freq, self.flash_size_freq)
)
if first_entrypoint != self.entrypoint:
print(
"WARNING: Entrypoint address in first header (0x%08x) disagrees "
"with second header (0x%08x). Using second value."
% (first_entrypoint, self.entrypoint)
)
# load all the usual segments
for _ in range(segments):
self.load_segment(load_file)
self.checksum = self.read_checksum(load_file)
self.verify()
def default_output_name(self, input_file):
"""Derive a default output name from the ELF name."""
irom_segment = self.get_irom_segment()
if irom_segment is not None:
irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START
else:
irom_offs = 0
return "%s-0x%05x.bin" % (
os.path.splitext(input_file)[0],
irom_offs & ~(ESPLoader.FLASH_SECTOR_SIZE - 1),
)
def save(self, filename):
with open(filename, "wb") as f:
# Save first header for irom0 segment
f.write(
struct.pack(
b"<BBBBI",
self.IMAGE_V2_MAGIC,
self.IMAGE_V2_SEGMENT,
self.flash_mode,
self.flash_size_freq,
self.entrypoint,
)
)
irom_segment = self.get_irom_segment()
if irom_segment is not None:
# save irom0 segment, make sure it has load addr 0 in the file
irom_segment = irom_segment.copy_with_new_addr(0)
irom_segment.pad_to_alignment(
16
) # irom_segment must end on a 16 byte boundary
self.save_segment(f, irom_segment)
# second header, matches V1 header and contains loadable segments
normal_segments = self.get_non_irom_segments()
self.write_common_header(f, normal_segments)
checksum = ESPLoader.ESP_CHECKSUM_MAGIC
for segment in normal_segments:
checksum = self.save_segment(f, segment, checksum)
self.append_checksum(f, checksum)
# calculate a crc32 of entire file and append
# (algorithm used by recent 8266 SDK bootloaders)
with open(filename, "rb") as f:
crc = esp8266_crc32(f.read())
with open(filename, "ab") as f:
f.write(struct.pack(b"<I", crc))
def esp8266_crc32(data):
"""
CRC32 algorithm used by 8266 SDK bootloader (and gen_appbin.py).
"""
crc = binascii.crc32(data, 0) & 0xFFFFFFFF
if crc & 0x80000000:
return crc ^ 0xFFFFFFFF
else:
return crc + 1
class ESP32FirmwareImage(BaseFirmwareImage):
"""ESP32 firmware image is very similar to V1 ESP8266 image,
except with an additional 16 byte reserved header at top of image,
and because of new flash mapping capabilities the flash-mapped regions
can be placed in the normal image (just @ 64kB padded offsets).
"""
ROM_LOADER = ESP32ROM
# ROM bootloader will read the wp_pin field if SPI flash
# pins are remapped via flash. IDF actually enables QIO only
# from software bootloader, so this can be ignored. But needs
# to be set to this value so ROM bootloader will skip it.
WP_PIN_DISABLED = 0xEE
EXTENDED_HEADER_STRUCT_FMT = "<BBBBHBHH" + ("B" * 4) + "B"
IROM_ALIGN = 65536
def __init__(self, load_file=None, append_digest=True):
super(ESP32FirmwareImage, self).__init__()
self.secure_pad = None
self.flash_mode = 0
self.flash_size_freq = 0
self.version = 1
self.wp_pin = self.WP_PIN_DISABLED
# SPI pin drive levels
self.clk_drv = 0
self.q_drv = 0
self.d_drv = 0
self.cs_drv = 0
self.hd_drv = 0
self.wp_drv = 0
self.chip_id = 0
self.min_rev = 0
self.min_rev_full = 0
self.max_rev_full = 0
self.append_digest = append_digest
if load_file is not None:
start = load_file.tell()
segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
self.load_extended_header(load_file)
for _ in range(segments):
self.load_segment(load_file)
self.checksum = self.read_checksum(load_file)
if self.append_digest:
end = load_file.tell()
self.stored_digest = load_file.read(32)
load_file.seek(start)
calc_digest = hashlib.sha256()
calc_digest.update(load_file.read(end - start))
self.calc_digest = calc_digest.digest() # TODO: decide what to do here?
self.verify()
def is_flash_addr(self, addr):
return (
self.ROM_LOADER.IROM_MAP_START <= addr < self.ROM_LOADER.IROM_MAP_END
) or (self.ROM_LOADER.DROM_MAP_START <= addr < self.ROM_LOADER.DROM_MAP_END)
def default_output_name(self, input_file):
"""Derive a default output name from the ELF name."""
return "%s.bin" % (os.path.splitext(input_file)[0])
def warn_if_unusual_segment(self, offset, size, is_irom_segment):
pass # TODO: add warnings for wrong ESP32 segment offset/size combinations
def save(self, filename):
total_segments = 0
with io.BytesIO() as f: # write file to memory first
self.write_common_header(f, self.segments)
# first 4 bytes of header are read by ROM bootloader for SPI
# config, but currently unused
self.save_extended_header(f)
checksum = ESPLoader.ESP_CHECKSUM_MAGIC
# split segments into flash-mapped vs ram-loaded,
# and take copies so we can mutate them
flash_segments = [
copy.deepcopy(s)
for s in sorted(self.segments, key=lambda s: s.addr)
if self.is_flash_addr(s.addr)
]
ram_segments = [
copy.deepcopy(s)
for s in sorted(self.segments, key=lambda s: s.addr)
if not self.is_flash_addr(s.addr)
]
# Patch to support 761 union bus memmap // TODO: ESPTOOL-512
# move ".flash.appdesc" segment to the top of the flash segment
for segment in flash_segments:
if segment.name == ".flash.appdesc":
flash_segments.remove(segment)
flash_segments.insert(0, segment)
break
# For the bootloader image
# move ".dram0.bootdesc" segment to the top of the ram segment
# So bootdesc will be at the very top of the binary at 0x20 offset
# (in the first segment).
for segment in ram_segments:
if segment.name == ".dram0.bootdesc":
ram_segments.remove(segment)
ram_segments.insert(0, segment)
break
# check for multiple ELF sections that are mapped in the same
# flash mapping region. This is usually a sign of a broken linker script,
# but if you have a legitimate use case then let us know
if len(flash_segments) > 0:
last_addr = flash_segments[0].addr
for segment in flash_segments[1:]:
if segment.addr // self.IROM_ALIGN == last_addr // self.IROM_ALIGN:
raise FatalError(
"Segment loaded at 0x%08x lands in same 64KB flash mapping "
"as segment loaded at 0x%08x. Can't generate binary. "
"Suggest changing linker script or ELF to merge sections."
% (segment.addr, last_addr)
)
last_addr = segment.addr
def get_alignment_data_needed(segment):
# Actual alignment (in data bytes) required for a segment header:
# positioned so that after we write the next 8 byte header,
# file_offs % IROM_ALIGN == segment.addr % IROM_ALIGN
#
# (this is because the segment's vaddr may not be IROM_ALIGNed,
# more likely is aligned IROM_ALIGN+0x18
# to account for the binary file header
align_past = (segment.addr % self.IROM_ALIGN) - self.SEG_HEADER_LEN
pad_len = (self.IROM_ALIGN - (f.tell() % self.IROM_ALIGN)) + align_past
if pad_len == 0 or pad_len == self.IROM_ALIGN:
return 0 # already aligned
# subtract SEG_HEADER_LEN a second time,
# as the padding block has a header as well
pad_len -= self.SEG_HEADER_LEN
if pad_len < 0:
pad_len += self.IROM_ALIGN
return pad_len
# try to fit each flash segment on a 64kB aligned boundary
# by padding with parts of the non-flash segments...
while len(flash_segments) > 0:
segment = flash_segments[0]
pad_len = get_alignment_data_needed(segment)
if pad_len > 0: # need to pad
if len(ram_segments) > 0 and pad_len > self.SEG_HEADER_LEN:
pad_segment = ram_segments[0].split_image(pad_len)
if len(ram_segments[0].data) == 0:
ram_segments.pop(0)
else:
pad_segment = ImageSegment(0, b"\x00" * pad_len, f.tell())
checksum = self.save_segment(f, pad_segment, checksum)
total_segments += 1
else:
# write the flash segment
assert (
f.tell() + 8
) % self.IROM_ALIGN == segment.addr % self.IROM_ALIGN
checksum = self.save_flash_segment(f, segment, checksum)
flash_segments.pop(0)
total_segments += 1
# flash segments all written, so write any remaining RAM segments
for segment in ram_segments:
checksum = self.save_segment(f, segment, checksum)
total_segments += 1
if self.secure_pad:
# pad the image so that after signing it will end on a a 64KB boundary.
# This ensures all mapped flash content will be verified.
if not self.append_digest:
raise FatalError(
"secure_pad only applies if a SHA-256 digest "
"is also appended to the image"
)
align_past = (f.tell() + self.SEG_HEADER_LEN) % self.IROM_ALIGN
# 16 byte aligned checksum
# (force the alignment to simplify calculations)
checksum_space = 16
if self.secure_pad == "1":
# after checksum: SHA-256 digest +
# (to be added by signing process) version,
# signature + 12 trailing bytes due to alignment
space_after_checksum = 32 + 4 + 64 + 12
elif self.secure_pad == "2": # Secure Boot V2
# after checksum: SHA-256 digest +
# signature sector,
# but we place signature sector after the 64KB boundary
space_after_checksum = 32
pad_len = (
self.IROM_ALIGN - align_past - checksum_space - space_after_checksum
) % self.IROM_ALIGN
pad_segment = ImageSegment(0, b"\x00" * pad_len, f.tell())
checksum = self.save_segment(f, pad_segment, checksum)
total_segments += 1
# done writing segments
self.append_checksum(f, checksum)
image_length = f.tell()
if self.secure_pad:
assert ((image_length + space_after_checksum) % self.IROM_ALIGN) == 0
# kinda hacky: go back to the initial header and write the new segment count
# that includes padding segments. This header is not checksummed
f.seek(1)
f.write(bytes([total_segments]))
if self.append_digest:
# calculate the SHA256 of the whole file and append it
f.seek(0)
digest = hashlib.sha256()
digest.update(f.read(image_length))
f.write(digest.digest())
if self.pad_to_size:
image_length = f.tell()
if image_length % self.pad_to_size != 0:
pad_by = self.pad_to_size - (image_length % self.pad_to_size)
f.write(b"\xff" * pad_by)
with open(filename, "wb") as real_file:
real_file.write(f.getvalue())
def load_extended_header(self, load_file):
def split_byte(n):
return (n & 0x0F, (n >> 4) & 0x0F)
fields = list(
struct.unpack(self.EXTENDED_HEADER_STRUCT_FMT, load_file.read(16))
)
self.wp_pin = fields[0]
# SPI pin drive stengths are two per byte
self.clk_drv, self.q_drv = split_byte(fields[1])
self.d_drv, self.cs_drv = split_byte(fields[2])
self.hd_drv, self.wp_drv = split_byte(fields[3])
self.chip_id = fields[4]
if self.chip_id != self.ROM_LOADER.IMAGE_CHIP_ID:
print(
(
"Unexpected chip id in image. Expected %d but value was %d. "
"Is this image for a different chip model?"
)
% (self.ROM_LOADER.IMAGE_CHIP_ID, self.chip_id)
)
self.min_rev = fields[5]
self.min_rev_full = fields[6]
self.max_rev_full = fields[7]
append_digest = fields[-1] # last byte is append_digest
if append_digest in [0, 1]:
self.append_digest = append_digest == 1
else:
raise RuntimeError(
"Invalid value for append_digest field (0x%02x). Should be 0 or 1.",
append_digest,
)
def save_extended_header(self, save_file):
def join_byte(ln, hn):
return (ln & 0x0F) + ((hn & 0x0F) << 4)
append_digest = 1 if self.append_digest else 0
fields = [
self.wp_pin,
join_byte(self.clk_drv, self.q_drv),
join_byte(self.d_drv, self.cs_drv),
join_byte(self.hd_drv, self.wp_drv),
self.ROM_LOADER.IMAGE_CHIP_ID,
self.min_rev,
self.min_rev_full,
self.max_rev_full,
]
fields += [0] * 4 # padding
fields += [append_digest]
packed = struct.pack(self.EXTENDED_HEADER_STRUCT_FMT, *fields)
save_file.write(packed)
class ESP8266V3FirmwareImage(ESP32FirmwareImage):
"""ESP8266 V3 firmware image is very similar to ESP32 image"""
EXTENDED_HEADER_STRUCT_FMT = "B" * 16
def is_flash_addr(self, addr):
return addr > ESP8266ROM.IROM_MAP_START
def save(self, filename):
total_segments = 0
with io.BytesIO() as f: # write file to memory first
self.write_common_header(f, self.segments)
checksum = ESPLoader.ESP_CHECKSUM_MAGIC
# split segments into flash-mapped vs ram-loaded,
# and take copies so we can mutate them
flash_segments = [
copy.deepcopy(s)
for s in sorted(self.segments, key=lambda s: s.addr)
if self.is_flash_addr(s.addr) and len(s.data)
]
ram_segments = [
copy.deepcopy(s)
for s in sorted(self.segments, key=lambda s: s.addr)
if not self.is_flash_addr(s.addr) and len(s.data)
]
# check for multiple ELF sections that are mapped in the same
# flash mapping region. This is usually a sign of a broken linker script,
# but if you have a legitimate use case then let us know
if len(flash_segments) > 0:
last_addr = flash_segments[0].addr
for segment in flash_segments[1:]:
if segment.addr // self.IROM_ALIGN == last_addr // self.IROM_ALIGN:
raise FatalError(
"Segment loaded at 0x%08x lands in same 64KB flash mapping "
"as segment loaded at 0x%08x. Can't generate binary. "
"Suggest changing linker script or ELF to merge sections."
% (segment.addr, last_addr)
)
last_addr = segment.addr
# try to fit each flash segment on a 64kB aligned boundary
# by padding with parts of the non-flash segments...
while len(flash_segments) > 0:
segment = flash_segments[0]
# remove 8 bytes empty data for insert segment header
if segment.name == ".flash.rodata":
segment.data = segment.data[8:]
# write the flash segment
checksum = self.save_segment(f, segment, checksum)
flash_segments.pop(0)
total_segments += 1
# flash segments all written, so write any remaining RAM segments
for segment in ram_segments:
checksum = self.save_segment(f, segment, checksum)
total_segments += 1
# done writing segments
self.append_checksum(f, checksum)
image_length = f.tell()
# kinda hacky: go back to the initial header and write the new segment count
# that includes padding segments. This header is not checksummed
f.seek(1)
f.write(bytes([total_segments]))
if self.append_digest:
# calculate the SHA256 of the whole file and append it
f.seek(0)
digest = hashlib.sha256()
digest.update(f.read(image_length))
f.write(digest.digest())
with open(filename, "wb") as real_file:
real_file.write(f.getvalue())
def load_extended_header(self, load_file):
def split_byte(n):
return (n & 0x0F, (n >> 4) & 0x0F)
fields = list(
struct.unpack(self.EXTENDED_HEADER_STRUCT_FMT, load_file.read(16))
)
self.wp_pin = fields[0]
# SPI pin drive stengths are two per byte
self.clk_drv, self.q_drv = split_byte(fields[1])
self.d_drv, self.cs_drv = split_byte(fields[2])
self.hd_drv, self.wp_drv = split_byte(fields[3])
if fields[15] in [0, 1]:
self.append_digest = fields[15] == 1
else:
raise RuntimeError(
"Invalid value for append_digest field (0x%02x). Should be 0 or 1.",
fields[15],
)
# remaining fields in the middle should all be zero
if any(f for f in fields[4:15] if f != 0):
print(
"Warning: some reserved header fields have non-zero values. "
"This image may be from a newer esptool.py?"
)
ESP32ROM.BOOTLOADER_IMAGE = ESP32FirmwareImage
class ESP32S2FirmwareImage(ESP32FirmwareImage):
"""ESP32S2 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32S2ROM
ESP32S2ROM.BOOTLOADER_IMAGE = ESP32S2FirmwareImage
class ESP32S3BETA2FirmwareImage(ESP32FirmwareImage):
"""ESP32S3 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32S3BETA2ROM
ESP32S3BETA2ROM.BOOTLOADER_IMAGE = ESP32S3BETA2FirmwareImage
class ESP32S3FirmwareImage(ESP32FirmwareImage):
"""ESP32S3 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32S3ROM
ESP32S3ROM.BOOTLOADER_IMAGE = ESP32S3FirmwareImage
class ESP32C3FirmwareImage(ESP32FirmwareImage):
"""ESP32C3 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32C3ROM
ESP32C3ROM.BOOTLOADER_IMAGE = ESP32C3FirmwareImage
class ESP32C6BETAFirmwareImage(ESP32FirmwareImage):
"""ESP32C6 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32C6BETAROM
ESP32C6BETAROM.BOOTLOADER_IMAGE = ESP32C6BETAFirmwareImage
class ESP32H2BETA1FirmwareImage(ESP32FirmwareImage):
"""ESP32H2 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32H2BETA1ROM
ESP32H2BETA1ROM.BOOTLOADER_IMAGE = ESP32H2BETA1FirmwareImage
class ESP32H2BETA2FirmwareImage(ESP32FirmwareImage):
"""ESP32H2 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32H2BETA2ROM
ESP32H2BETA2ROM.BOOTLOADER_IMAGE = ESP32H2BETA2FirmwareImage
class ESP32C2FirmwareImage(ESP32FirmwareImage):
"""ESP32C2 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32C2ROM
def set_mmu_page_size(self, size):
if size not in [16384, 32768, 65536]:
raise FatalError(
"{} bytes is not a valid ESP32-C2 page size, "
"select from 64KB, 32KB, 16KB.".format(size)
)
self.IROM_ALIGN = size
ESP32C2ROM.BOOTLOADER_IMAGE = ESP32C2FirmwareImage
class ESP32C6FirmwareImage(ESP32FirmwareImage):
"""ESP32C6 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32C6ROM
def set_mmu_page_size(self, size):
if size not in [8192, 16384, 32768, 65536]:
raise FatalError(
"{} bytes is not a valid ESP32-C6 page size, "
"select from 64KB, 32KB, 16KB, 8KB.".format(size)
)
self.IROM_ALIGN = size
ESP32C6ROM.BOOTLOADER_IMAGE = ESP32C6FirmwareImage
class ESP32H2FirmwareImage(ESP32C6FirmwareImage):
"""ESP32H2 Firmware Image almost exactly the same as ESP32FirmwareImage"""
ROM_LOADER = ESP32H2ROM
ESP32H2ROM.BOOTLOADER_IMAGE = ESP32H2FirmwareImage
class ELFFile(object):
SEC_TYPE_PROGBITS = 0x01
SEC_TYPE_STRTAB = 0x03
SEC_TYPE_INITARRAY = 0x0E
SEC_TYPE_FINIARRAY = 0x0F
PROG_SEC_TYPES = (SEC_TYPE_PROGBITS, SEC_TYPE_INITARRAY, SEC_TYPE_FINIARRAY)
LEN_SEC_HEADER = 0x28
SEG_TYPE_LOAD = 0x01
LEN_SEG_HEADER = 0x20
def __init__(self, name):
# Load sections from the ELF file
self.name = name
with open(self.name, "rb") as f:
self._read_elf_file(f)
def get_section(self, section_name):
for s in self.sections:
if s.name == section_name:
return s
raise ValueError("No section %s in ELF file" % section_name)
def _read_elf_file(self, f):
# read the ELF file header
LEN_FILE_HEADER = 0x34
try:
(
ident,
_type,
machine,
_version,
self.entrypoint,
_phoff,
shoff,
_flags,
_ehsize,
_phentsize,
_phnum,
shentsize,
shnum,
shstrndx,
) = struct.unpack("<16sHHLLLLLHHHHHH", f.read(LEN_FILE_HEADER))
except struct.error as e:
raise FatalError(
"Failed to read a valid ELF header from %s: %s" % (self.name, e)
)
if byte(ident, 0) != 0x7F or ident[1:4] != b"ELF":
raise FatalError("%s has invalid ELF magic header" % self.name)
if machine not in [0x5E, 0xF3]:
raise FatalError(
"%s does not appear to be an Xtensa or an RISCV ELF file. "
"e_machine=%04x" % (self.name, machine)
)
if shentsize != self.LEN_SEC_HEADER:
raise FatalError(
"%s has unexpected section header entry size 0x%x (not 0x%x)"
% (self.name, shentsize, self.LEN_SEC_HEADER)
)
if shnum == 0:
raise FatalError("%s has 0 section headers" % (self.name))
self._read_sections(f, shoff, shnum, shstrndx)
self._read_segments(f, _phoff, _phnum, shstrndx)
def _read_sections(self, f, section_header_offs, section_header_count, shstrndx):
f.seek(section_header_offs)
len_bytes = section_header_count * self.LEN_SEC_HEADER
section_header = f.read(len_bytes)
if len(section_header) == 0:
raise FatalError(
"No section header found at offset %04x in ELF file."
% section_header_offs
)
if len(section_header) != (len_bytes):
raise FatalError(
"Only read 0x%x bytes from section header (expected 0x%x.) "
"Truncated ELF file?" % (len(section_header), len_bytes)
)
# walk through the section header and extract all sections
section_header_offsets = range(0, len(section_header), self.LEN_SEC_HEADER)
def read_section_header(offs):
name_offs, sec_type, _flags, lma, sec_offs, size = struct.unpack_from(
"<LLLLLL", section_header[offs:]
)
return (name_offs, sec_type, lma, size, sec_offs)
all_sections = [read_section_header(offs) for offs in section_header_offsets]
prog_sections = [s for s in all_sections if s[1] in ELFFile.PROG_SEC_TYPES]
# search for the string table section
if not (shstrndx * self.LEN_SEC_HEADER) in section_header_offsets:
raise FatalError("ELF file has no STRTAB section at shstrndx %d" % shstrndx)
_, sec_type, _, sec_size, sec_offs = read_section_header(
shstrndx * self.LEN_SEC_HEADER
)
if sec_type != ELFFile.SEC_TYPE_STRTAB:
print(
"WARNING: ELF file has incorrect STRTAB section type 0x%02x" % sec_type
)
f.seek(sec_offs)
string_table = f.read(sec_size)
# build the real list of ELFSections by reading the actual section names from
# the string table section, and actual data for each section
# from the ELF file itself
def lookup_string(offs):
raw = string_table[offs:]
return raw[: raw.index(b"\x00")]
def read_data(offs, size):
f.seek(offs)
return f.read(size)
prog_sections = [
ELFSection(lookup_string(n_offs), lma, read_data(offs, size))
for (n_offs, _type, lma, size, offs) in prog_sections
if lma != 0 and size > 0
]
self.sections = prog_sections
def _read_segments(self, f, segment_header_offs, segment_header_count, shstrndx):
f.seek(segment_header_offs)
len_bytes = segment_header_count * self.LEN_SEG_HEADER
segment_header = f.read(len_bytes)
if len(segment_header) == 0:
raise FatalError(
"No segment header found at offset %04x in ELF file."
% segment_header_offs
)
if len(segment_header) != (len_bytes):
raise FatalError(
"Only read 0x%x bytes from segment header (expected 0x%x.) "
"Truncated ELF file?" % (len(segment_header), len_bytes)
)
# walk through the segment header and extract all segments
segment_header_offsets = range(0, len(segment_header), self.LEN_SEG_HEADER)
def read_segment_header(offs):
(
seg_type,
seg_offs,
_vaddr,
lma,
size,
_memsize,
_flags,
_align,
) = struct.unpack_from("<LLLLLLLL", segment_header[offs:])
return (seg_type, lma, size, seg_offs)
all_segments = [read_segment_header(offs) for offs in segment_header_offsets]
prog_segments = [s for s in all_segments if s[0] == ELFFile.SEG_TYPE_LOAD]
def read_data(offs, size):
f.seek(offs)
return f.read(size)
prog_segments = [
ELFSection(b"PHDR", lma, read_data(offs, size))
for (_type, lma, size, offs) in prog_segments
if lma != 0 and size > 0
]
self.segments = prog_segments
def sha256(self):
# return SHA256 hash of the input ELF file
sha256 = hashlib.sha256()
with open(self.name, "rb") as f:
sha256.update(f.read())
return sha256.digest()
| 46,725 | Python | .py | 1,023 | 33.605083 | 88 | 0.578515 | OLIMEX/RVPC | 8 | 2 | 1 | GPL-3.0 | 9/5/2024, 10:48:43 PM (Europe/Amsterdam) |
2,289,605 | loader.py | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/loader.py | # SPDX-FileCopyrightText: 2014-2023 Fredrik Ahlberg, Angus Gratton,
# Espressif Systems (Shanghai) CO LTD, other contributors as noted.
#
# SPDX-License-Identifier: GPL-2.0-or-later
import base64
import hashlib
import itertools
import json
import os
import re
import string
import struct
import sys
import time
from .config import load_config_file
from .reset import (
ClassicReset,
CustomReset,
DEFAULT_RESET_DELAY,
HardReset,
USBJTAGSerialReset,
UnixTightReset,
)
from .util import FatalError, NotImplementedInROMError, UnsupportedCommandError
from .util import byte, hexify, mask_to_shift, pad_to, strip_chip_name
try:
import serial
except ImportError:
print(
"Pyserial is not installed for %s. "
"Check the README for installation instructions." % (sys.executable)
)
raise
# check 'serial' is 'pyserial' and not 'serial'
# ref. https://github.com/espressif/esptool/issues/269
try:
if "serialization" in serial.__doc__ and "deserialization" in serial.__doc__:
raise ImportError(
"esptool.py depends on pyserial, but there is a conflict with a currently "
"installed package named 'serial'.\n"
"You may work around this by 'pip uninstall serial; pip install pyserial' "
"but this may break other installed Python software "
"that depends on 'serial'.\n"
"There is no good fix for this right now, "
"apart from configuring virtualenvs. "
"See https://github.com/espressif/esptool/issues/269#issuecomment-385298196"
" for discussion of the underlying issue(s)."
)
except TypeError:
pass # __doc__ returns None for pyserial
try:
import serial.tools.list_ports as list_ports
except ImportError:
print(
"The installed version (%s) of pyserial appears to be too old for esptool.py "
"(Python interpreter %s). Check the README for installation instructions."
% (sys.VERSION, sys.executable)
)
raise
except Exception:
if sys.platform == "darwin":
# swallow the exception, this is a known issue in pyserial+macOS Big Sur preview
# ref https://github.com/espressif/esptool/issues/540
list_ports = None
else:
raise
cfg, _ = load_config_file()
cfg = cfg["esptool"]
# Timeout for most flash operations
DEFAULT_TIMEOUT = cfg.getfloat("timeout", 3)
# Timeout for full chip erase
CHIP_ERASE_TIMEOUT = cfg.getfloat("chip_erase_timeout", 120)
# Longest any command can run
MAX_TIMEOUT = cfg.getfloat("max_timeout", CHIP_ERASE_TIMEOUT * 2)
# Timeout for syncing with bootloader
SYNC_TIMEOUT = cfg.getfloat("sync_timeout", 0.1)
# Timeout (per megabyte) for calculating md5sum
MD5_TIMEOUT_PER_MB = cfg.getfloat("md5_timeout_per_mb", 8)
# Timeout (per megabyte) for erasing a region
ERASE_REGION_TIMEOUT_PER_MB = cfg.getfloat("erase_region_timeout_per_mb", 30)
# Timeout (per megabyte) for erasing and writing data
ERASE_WRITE_TIMEOUT_PER_MB = cfg.getfloat("erase_write_timeout_per_mb", 40)
# Short timeout for ESP_MEM_END, as it may never respond
MEM_END_ROM_TIMEOUT = cfg.getfloat("mem_end_rom_timeout", 0.2)
# Timeout for serial port write
DEFAULT_SERIAL_WRITE_TIMEOUT = cfg.getfloat("serial_write_timeout", 10)
# Default number of times to try connection
DEFAULT_CONNECT_ATTEMPTS = cfg.getint("connect_attempts", 7)
# Number of times to try writing a data block
WRITE_BLOCK_ATTEMPTS = cfg.getint("write_block_attempts", 3)
STUBS_DIR = os.path.join(os.path.dirname(__file__), "targets", "stub_flasher")
def get_stub_json_path(chip_name):
chip_name = strip_chip_name(chip_name)
chip_name = chip_name.replace("esp", "")
return os.path.join(STUBS_DIR, f"stub_flasher_{chip_name}.json")
def timeout_per_mb(seconds_per_mb, size_bytes):
"""Scales timeouts which are size-specific"""
result = seconds_per_mb * (size_bytes / 1e6)
if result < DEFAULT_TIMEOUT:
return DEFAULT_TIMEOUT
return result
def check_supported_function(func, check_func):
"""
Decorator implementation that wraps a check around an ESPLoader
bootloader function to check if it's supported.
This is used to capture the multidimensional differences in
functionality between the ESP8266 & ESP32 (and later chips) ROM loaders, and the
software stub that runs on these. Not possible to do this cleanly
via inheritance alone.
"""
def inner(*args, **kwargs):
obj = args[0]
if check_func(obj):
return func(*args, **kwargs)
else:
raise NotImplementedInROMError(obj, func)
return inner
def stub_function_only(func):
"""Attribute for a function only supported in the software stub loader"""
return check_supported_function(func, lambda o: o.IS_STUB)
def stub_and_esp32_function_only(func):
"""Attribute for a function only supported by stubs or ESP32 and later chips ROM"""
return check_supported_function(
func, lambda o: o.IS_STUB or o.CHIP_NAME not in ["ESP8266"]
)
def esp32s3_or_newer_function_only(func):
"""Attribute for a function only supported by ESP32S3 and later chips ROM"""
return check_supported_function(
func, lambda o: o.CHIP_NAME not in ["ESP8266", "ESP32", "ESP32-S2"]
)
class StubFlasher:
def __init__(self, json_path):
with open(json_path) as json_file:
stub = json.load(json_file)
self.text = base64.b64decode(stub["text"])
self.text_start = stub["text_start"]
self.entry = stub["entry"]
try:
self.data = base64.b64decode(stub["data"])
self.data_start = stub["data_start"]
except KeyError:
self.data = None
self.data_start = None
class ESPLoader(object):
"""Base class providing access to ESP ROM & software stub bootloaders.
Subclasses provide ESP8266 & ESP32 Family specific functionality.
Don't instantiate this base class directly, either instantiate a subclass or
call cmds.detect_chip() which will interrogate the chip and return the
appropriate subclass instance.
"""
CHIP_NAME = "Espressif device"
IS_STUB = False
FPGA_SLOW_BOOT = False
DEFAULT_PORT = "/dev/ttyUSB0"
USES_RFC2217 = False
# Commands supported by ESP8266 ROM bootloader
ESP_FLASH_BEGIN = 0x02
ESP_FLASH_DATA = 0x03
ESP_FLASH_END = 0x04
ESP_MEM_BEGIN = 0x05
ESP_MEM_END = 0x06
ESP_MEM_DATA = 0x07
ESP_SYNC = 0x08
ESP_WRITE_REG = 0x09
ESP_READ_REG = 0x0A
# Some comands supported by ESP32 and later chips ROM bootloader (or -8266 w/ stub)
ESP_SPI_SET_PARAMS = 0x0B
ESP_SPI_ATTACH = 0x0D
ESP_READ_FLASH_SLOW = 0x0E # ROM only, much slower than the stub flash read
ESP_CHANGE_BAUDRATE = 0x0F
ESP_FLASH_DEFL_BEGIN = 0x10
ESP_FLASH_DEFL_DATA = 0x11
ESP_FLASH_DEFL_END = 0x12
ESP_SPI_FLASH_MD5 = 0x13
# Commands supported by ESP32-S2 and later chips ROM bootloader only
ESP_GET_SECURITY_INFO = 0x14
# Some commands supported by stub only
ESP_ERASE_FLASH = 0xD0
ESP_ERASE_REGION = 0xD1
ESP_READ_FLASH = 0xD2
ESP_RUN_USER_CODE = 0xD3
# Flash encryption encrypted data command
ESP_FLASH_ENCRYPT_DATA = 0xD4
# Response code(s) sent by ROM
ROM_INVALID_RECV_MSG = 0x05 # response if an invalid message is received
# Maximum block sized for RAM and Flash writes, respectively.
ESP_RAM_BLOCK = 0x1800
FLASH_WRITE_SIZE = 0x400
# Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
ESP_ROM_BAUD = 115200
# First byte of the application image
ESP_IMAGE_MAGIC = 0xE9
# Initial state for the checksum routine
ESP_CHECKSUM_MAGIC = 0xEF
# Flash sector size, minimum unit of erase.
FLASH_SECTOR_SIZE = 0x1000
UART_DATE_REG_ADDR = 0x60000078
# This ROM address has a different value on each chip model
CHIP_DETECT_MAGIC_REG_ADDR = 0x40001000
UART_CLKDIV_MASK = 0xFFFFF
# Memory addresses
IROM_MAP_START = 0x40200000
IROM_MAP_END = 0x40300000
# The number of bytes in the UART response that signify command status
STATUS_BYTES_LENGTH = 2
# Bootloader flashing offset
BOOTLOADER_FLASH_OFFSET = 0x0
# ROM supports an encrypted flashing mode
SUPPORTS_ENCRYPTED_FLASH = False
# Response to ESP_SYNC might indicate that flasher stub is running
# instead of the ROM bootloader
sync_stub_detected = False
# Device PIDs
USB_JTAG_SERIAL_PID = 0x1001
# Chip IDs that are no longer supported by esptool
UNSUPPORTED_CHIPS = {6: "ESP32-S3(beta 3)"}
def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
"""Base constructor for ESPLoader bootloader interaction
Don't call this constructor, either instantiate a specific
ROM class directly, or use cmds.detect_chip().
This base class has all of the instance methods for bootloader
functionality supported across various chips & stub
loaders. Subclasses replace the functions they don't support
with ones which throw NotImplementedInROMError().
"""
# True if esptool detects the ROM is in Secure Download Mode
self.secure_download_mode = False
# True if esptool detects conditions which require the stub to be disabled
self.stub_is_disabled = False
# Device-and-runtime-specific cache
self.cache = {
"flash_id": None,
"chip_id": None,
"uart_no": None,
"usb_pid": None,
}
if isinstance(port, str):
try:
self._port = serial.serial_for_url(port)
except serial.serialutil.SerialException:
raise FatalError(f"Could not open {port}, the port doesn't exist")
else:
self._port = port
self._slip_reader = slip_reader(self._port, self.trace)
# setting baud rate in a separate step is a workaround for
# CH341 driver on some Linux versions (this opens at 9600 then
# sets), shouldn't matter for other platforms/drivers. See
# https://github.com/espressif/esptool/issues/44#issuecomment-107094446
self._set_port_baudrate(baud)
self._trace_enabled = trace_enabled
# set write timeout, to prevent esptool blocked at write forever.
try:
self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT
except NotImplementedError:
# no write timeout for RFC2217 ports
# need to set the property back to None or it will continue to fail
self._port.write_timeout = None
@property
def serial_port(self):
return self._port.port
def _set_port_baudrate(self, baud):
try:
self._port.baudrate = baud
except IOError:
raise FatalError(
"Failed to set baud rate %d. The driver may not support this rate."
% baud
)
def read(self):
"""Read a SLIP packet from the serial port"""
return next(self._slip_reader)
def write(self, packet):
"""Write bytes to the serial port while performing SLIP escaping"""
buf = (
b"\xc0"
+ (packet.replace(b"\xdb", b"\xdb\xdd").replace(b"\xc0", b"\xdb\xdc"))
+ b"\xc0"
)
self.trace("Write %d bytes: %s", len(buf), HexFormatter(buf))
self._port.write(buf)
def trace(self, message, *format_args):
if self._trace_enabled:
now = time.time()
try:
delta = now - self._last_trace
except AttributeError:
delta = 0.0
self._last_trace = now
prefix = "TRACE +%.3f " % delta
print(prefix + (message % format_args))
@staticmethod
def checksum(data, state=ESP_CHECKSUM_MAGIC):
"""Calculate checksum of a blob, as it is defined by the ROM"""
for b in data:
state ^= b
return state
def command(
self,
op=None,
data=b"",
chk=0,
wait_response=True,
timeout=DEFAULT_TIMEOUT,
):
"""Send a request and read the response"""
saved_timeout = self._port.timeout
new_timeout = min(timeout, MAX_TIMEOUT)
if new_timeout != saved_timeout:
self._port.timeout = new_timeout
try:
if op is not None:
self.trace(
"command op=0x%02x data len=%s wait_response=%d "
"timeout=%.3f data=%s",
op,
len(data),
1 if wait_response else 0,
timeout,
HexFormatter(data),
)
pkt = struct.pack(b"<BBHI", 0x00, op, len(data), chk) + data
self.write(pkt)
if not wait_response:
return
# tries to get a response until that response has the
# same operation as the request or a retries limit has
# exceeded. This is needed for some esp8266s that
# reply with more sync responses than expected.
for retry in range(100):
p = self.read()
if len(p) < 8:
continue
(resp, op_ret, len_ret, val) = struct.unpack("<BBHI", p[:8])
if resp != 1:
continue
data = p[8:]
if op is None or op_ret == op:
return val, data
if byte(data, 0) != 0 and byte(data, 1) == self.ROM_INVALID_RECV_MSG:
# Unsupported read_reg can result in
# more than one error response for some reason
self.flush_input()
raise UnsupportedCommandError(self, op)
finally:
if new_timeout != saved_timeout:
self._port.timeout = saved_timeout
raise FatalError("Response doesn't match request")
def check_command(
self, op_description, op=None, data=b"", chk=0, timeout=DEFAULT_TIMEOUT
):
"""
Execute a command with 'command', check the result code and throw an appropriate
FatalError if it fails.
Returns the "result" of a successful command.
"""
val, data = self.command(op, data, chk, timeout=timeout)
# things are a bit weird here, bear with us
# the status bytes are the last 2/4 bytes in the data (depending on chip)
if len(data) < self.STATUS_BYTES_LENGTH:
raise FatalError(
"Failed to %s. Only got %d byte status response."
% (op_description, len(data))
)
status_bytes = data[-self.STATUS_BYTES_LENGTH :]
# only care if the first one is non-zero. If it is, the second byte is a reason.
if byte(status_bytes, 0) != 0:
raise FatalError.WithResult("Failed to %s" % op_description, status_bytes)
# if we had more data than just the status bytes, return it as the result
# (this is used by the md5sum command, maybe other commands?)
if len(data) > self.STATUS_BYTES_LENGTH:
return data[: -self.STATUS_BYTES_LENGTH]
else:
# otherwise, just return the 'val' field which comes from the reply header
# (this is used by read_reg)
return val
def flush_input(self):
self._port.flushInput()
self._slip_reader = slip_reader(self._port, self.trace)
def sync(self):
val, _ = self.command(
self.ESP_SYNC, b"\x07\x07\x12\x20" + 32 * b"\x55", timeout=SYNC_TIMEOUT
)
# ROM bootloaders send some non-zero "val" response. The flasher stub sends 0.
# If we receive 0 then it probably indicates that the chip wasn't or couldn't be
# reseted properly and esptool is talking to the flasher stub.
self.sync_stub_detected = val == 0
for _ in range(7):
val, _ = self.command()
self.sync_stub_detected &= val == 0
def _get_pid(self):
if self.cache["usb_pid"] is not None:
return self.cache["usb_pid"]
if list_ports is None:
print(
"\nListing all serial ports is currently not available. "
"Can't get device PID."
)
return
active_port = self._port.port
# Pyserial only identifies regular ports, URL handlers are not supported
if not active_port.lower().startswith(("com", "/dev/")):
print(
"\nDevice PID identification is only supported on "
"COM and /dev/ serial ports."
)
return
# Return the real path if the active port is a symlink
if active_port.startswith("/dev/") and os.path.islink(active_port):
active_port = os.path.realpath(active_port)
active_ports = [active_port]
# The "cu" (call-up) device has to be used for outgoing communication on MacOS
if sys.platform == "darwin" and "tty" in active_port:
active_ports.append(active_port.replace("tty", "cu"))
ports = list_ports.comports()
for p in ports:
if p.device in active_ports:
self.cache["usb_pid"] = p.pid
return p.pid
print(
f"\nFailed to get PID of a device on {active_port}, "
"using standard reset sequence."
)
def _connect_attempt(self, reset_strategy, mode="default_reset"):
"""A single connection attempt"""
last_error = None
boot_log_detected = False
download_mode = False
# If we're doing no_sync, we're likely communicating as a pass through
# with an intermediate device to the ESP32
if mode == "no_reset_no_sync":
return last_error
if mode != "no_reset":
if not self.USES_RFC2217: # Might block on rfc2217 ports
# Empty serial buffer to isolate boot log
self._port.reset_input_buffer()
reset_strategy() # Reset the chip to bootloader (download mode)
# Detect the ROM boot log and check actual boot mode (ESP32 and later only)
waiting = self._port.inWaiting()
read_bytes = self._port.read(waiting)
data = re.search(
b"boot:(0x[0-9a-fA-F]+)(.*waiting for download)?", read_bytes, re.DOTALL
)
if data is not None:
boot_log_detected = True
boot_mode = data.group(1)
download_mode = data.group(2) is not None
for _ in range(5):
try:
self.flush_input()
self._port.flushOutput()
self.sync()
return None
except FatalError as e:
print(".", end="")
sys.stdout.flush()
time.sleep(0.05)
last_error = e
if boot_log_detected:
last_error = FatalError(
"Wrong boot mode detected ({})! "
"The chip needs to be in download mode.".format(
boot_mode.decode("utf-8")
)
)
if download_mode:
last_error = FatalError(
"Download mode successfully detected, but getting no sync reply: "
"The serial TX path seems to be down."
)
return last_error
def get_memory_region(self, name):
"""
Returns a tuple of (start, end) for the memory map entry with the given name,
or None if it doesn't exist
"""
try:
return [(start, end) for (start, end, n) in self.MEMORY_MAP if n == name][0]
except IndexError:
return None
def _construct_reset_strategy_sequence(self, mode):
"""
Constructs a sequence of reset strategies based on the OS,
used ESP chip, external settings, and environment variables.
Returns a tuple of one or more reset strategies to be tried sequentially.
"""
cfg_custom_reset_sequence = cfg.get("custom_reset_sequence")
if cfg_custom_reset_sequence is not None:
return (CustomReset(self._port, cfg_custom_reset_sequence),)
cfg_reset_delay = cfg.getfloat("reset_delay")
if cfg_reset_delay is not None:
delay = extra_delay = cfg_reset_delay
else:
delay = DEFAULT_RESET_DELAY
extra_delay = DEFAULT_RESET_DELAY + 0.5
# This FPGA delay is for Espressif internal use
if (
self.FPGA_SLOW_BOOT
and os.environ.get("ESPTOOL_ENV_FPGA", "").strip() == "1"
):
delay = extra_delay = 7
# USB-JTAG/Serial mode
if mode == "usb_reset" or self._get_pid() == self.USB_JTAG_SERIAL_PID:
return (USBJTAGSerialReset(self._port),)
# USB-to-Serial bridge
if os.name != "nt" and not self._port.name.startswith("rfc2217:"):
return (
UnixTightReset(self._port, delay),
UnixTightReset(self._port, extra_delay),
ClassicReset(self._port, delay),
ClassicReset(self._port, extra_delay),
)
return (
ClassicReset(self._port, delay),
ClassicReset(self._port, extra_delay),
)
def connect(
self,
mode="default_reset",
attempts=DEFAULT_CONNECT_ATTEMPTS,
detecting=False,
warnings=True,
):
"""Try connecting repeatedly until successful, or giving up"""
if warnings and mode in ["no_reset", "no_reset_no_sync"]:
print(
'WARNING: Pre-connection option "{}" was selected.'.format(mode),
"Connection may fail if the chip is not in bootloader "
"or flasher stub mode.",
)
print("Connecting...", end="")
sys.stdout.flush()
last_error = None
reset_sequence = self._construct_reset_strategy_sequence(mode)
try:
for _, reset_strategy in zip(
range(attempts) if attempts > 0 else itertools.count(),
itertools.cycle(reset_sequence),
):
last_error = self._connect_attempt(reset_strategy, mode)
if last_error is None:
break
finally:
print("") # end 'Connecting...' line
if last_error is not None:
raise FatalError(
"Failed to connect to {}: {}"
"\nFor troubleshooting steps visit: "
"https://docs.espressif.com/projects/esptool/en/latest/troubleshooting.html".format( # noqa E501
self.CHIP_NAME, last_error
)
)
if not detecting:
try:
from .targets import ROM_LIST
# check the date code registers match what we expect to see
chip_magic_value = self.read_reg(ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR)
if chip_magic_value not in self.CHIP_DETECT_MAGIC_VALUE:
actually = None
for cls in ROM_LIST:
if chip_magic_value in cls.CHIP_DETECT_MAGIC_VALUE:
actually = cls
break
if warnings and actually is None:
print(
"WARNING: This chip doesn't appear to be a %s "
"(chip magic value 0x%08x). "
"Probably it is unsupported by this version of esptool."
% (self.CHIP_NAME, chip_magic_value)
)
else:
raise FatalError(
"This chip is %s not %s. Wrong --chip argument?"
% (actually.CHIP_NAME, self.CHIP_NAME)
)
except UnsupportedCommandError:
self.secure_download_mode = True
try:
self.check_chip_id()
except UnsupportedCommandError:
# Fix for ROM not responding in SDM, reconnect and try again
if self.secure_download_mode:
self._connect_attempt(mode, reset_sequence[0])
self.check_chip_id()
else:
raise
self._post_connect()
def _post_connect(self):
"""
Additional initialization hook, may be overridden by the chip-specific class.
Gets called after connect, and after auto-detection.
"""
pass
def read_reg(self, addr, timeout=DEFAULT_TIMEOUT):
"""Read memory address in target"""
# we don't call check_command here because read_reg() function is called
# when detecting chip type, and the way we check for success
# (STATUS_BYTES_LENGTH) is different for different chip types (!)
val, data = self.command(
self.ESP_READ_REG, struct.pack("<I", addr), timeout=timeout
)
if byte(data, 0) != 0:
raise FatalError.WithResult(
"Failed to read register address %08x" % addr, data
)
return val
def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0, delay_after_us=0):
"""Write to memory address in target"""
command = struct.pack("<IIII", addr, value, mask, delay_us)
if delay_after_us > 0:
# add a dummy write to a date register as an excuse to have a delay
command += struct.pack(
"<IIII", self.UART_DATE_REG_ADDR, 0, 0, delay_after_us
)
return self.check_command("write target memory", self.ESP_WRITE_REG, command)
def update_reg(self, addr, mask, new_val):
"""
Update register at 'addr', replace the bits masked out by 'mask'
with new_val. new_val is shifted left to match the LSB of 'mask'
Returns just-written value of register.
"""
shift = mask_to_shift(mask)
val = self.read_reg(addr)
val &= ~mask
val |= (new_val << shift) & mask
self.write_reg(addr, val)
return val
def mem_begin(self, size, blocks, blocksize, offset):
"""Start downloading an application image to RAM"""
# check we're not going to overwrite a running stub with this data
if self.IS_STUB:
stub = StubFlasher(get_stub_json_path(self.CHIP_NAME))
load_start = offset
load_end = offset + size
for start, end in [
(stub.data_start, stub.data_start + len(stub.data)),
(stub.text_start, stub.text_start + len(stub.text)),
]:
if load_start < end and load_end > start:
raise FatalError(
"Software loader is resident at 0x%08x-0x%08x. "
"Can't load binary at overlapping address range 0x%08x-0x%08x. "
"Either change binary loading address, or use the --no-stub "
"option to disable the software loader."
% (start, end, load_start, load_end)
)
return self.check_command(
"enter RAM download mode",
self.ESP_MEM_BEGIN,
struct.pack("<IIII", size, blocks, blocksize, offset),
)
def mem_block(self, data, seq):
"""Send a block of an image to RAM"""
return self.check_command(
"write to target RAM",
self.ESP_MEM_DATA,
struct.pack("<IIII", len(data), seq, 0, 0) + data,
self.checksum(data),
)
def mem_finish(self, entrypoint=0):
"""Leave download mode and run the application"""
# Sending ESP_MEM_END usually sends a correct response back, however sometimes
# (with ROM loader) the executed code may reset the UART or change the baud rate
# before the transmit FIFO is empty. So in these cases we set a short timeout
# and ignore errors.
timeout = DEFAULT_TIMEOUT if self.IS_STUB else MEM_END_ROM_TIMEOUT
data = struct.pack("<II", int(entrypoint == 0), entrypoint)
try:
return self.check_command(
"leave RAM download mode", self.ESP_MEM_END, data=data, timeout=timeout
)
except FatalError:
if self.IS_STUB:
raise
pass
def flash_begin(self, size, offset, begin_rom_encrypted=False):
"""
Start downloading to Flash (performs an erase)
Returns number of blocks (of size self.FLASH_WRITE_SIZE) to write.
"""
num_blocks = (size + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
erase_size = self.get_erase_size(offset, size)
t = time.time()
if self.IS_STUB:
timeout = DEFAULT_TIMEOUT
else:
timeout = timeout_per_mb(
ERASE_REGION_TIMEOUT_PER_MB, size
) # ROM performs the erase up front
params = struct.pack(
"<IIII", erase_size, num_blocks, self.FLASH_WRITE_SIZE, offset
)
if self.SUPPORTS_ENCRYPTED_FLASH and not self.IS_STUB:
params += struct.pack("<I", 1 if begin_rom_encrypted else 0)
self.check_command(
"enter Flash download mode", self.ESP_FLASH_BEGIN, params, timeout=timeout
)
if size != 0 and not self.IS_STUB:
print("Took %.2fs to erase flash block" % (time.time() - t))
return num_blocks
def flash_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
"""Write block to flash, retry if fail"""
for attempts_left in range(WRITE_BLOCK_ATTEMPTS - 1, -1, -1):
try:
self.check_command(
"write to target Flash after seq %d" % seq,
self.ESP_FLASH_DATA,
struct.pack("<IIII", len(data), seq, 0, 0) + data,
self.checksum(data),
timeout=timeout,
)
break
except FatalError:
if attempts_left:
self.trace(
"Block write failed, "
f"retrying with {attempts_left} attempts left"
)
else:
raise
def flash_encrypt_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
"""Encrypt, write block to flash, retry if fail"""
if self.SUPPORTS_ENCRYPTED_FLASH and not self.IS_STUB:
# ROM support performs the encrypted writes via the normal write command,
# triggered by flash_begin(begin_rom_encrypted=True)
return self.flash_block(data, seq, timeout)
for attempts_left in range(WRITE_BLOCK_ATTEMPTS - 1, -1, -1):
try:
self.check_command(
"Write encrypted to target Flash after seq %d" % seq,
self.ESP_FLASH_ENCRYPT_DATA,
struct.pack("<IIII", len(data), seq, 0, 0) + data,
self.checksum(data),
timeout=timeout,
)
break
except FatalError:
if attempts_left:
self.trace(
"Encrypted block write failed, "
f"retrying with {attempts_left} attempts left"
)
else:
raise
def flash_finish(self, reboot=False):
"""Leave flash mode and run/reboot"""
pkt = struct.pack("<I", int(not reboot))
# stub sends a reply to this command
self.check_command("leave Flash mode", self.ESP_FLASH_END, pkt)
def run(self, reboot=False):
"""Run application code in flash"""
# Fake flash begin immediately followed by flash end
self.flash_begin(0, 0)
self.flash_finish(reboot)
def flash_id(self):
"""Read SPI flash manufacturer and device id"""
if self.cache["flash_id"] is None:
SPIFLASH_RDID = 0x9F
self.cache["flash_id"] = self.run_spiflash_command(SPIFLASH_RDID, b"", 24)
return self.cache["flash_id"]
def flash_type(self):
"""Read flash type bit field from eFuse. Returns 0, 1, None (not present)"""
return None # not implemented for all chip targets
def get_security_info(self):
res = self.check_command("get security info", self.ESP_GET_SECURITY_INFO, b"")
esp32s2 = True if len(res) == 12 else False
res = struct.unpack("<IBBBBBBBB" if esp32s2 else "<IBBBBBBBBII", res)
return {
"flags": res[0],
"flash_crypt_cnt": res[1],
"key_purposes": res[2:9],
"chip_id": None if esp32s2 else res[9],
"api_version": None if esp32s2 else res[10],
}
@esp32s3_or_newer_function_only
def get_chip_id(self):
if self.cache["chip_id"] is None:
res = self.check_command(
"get security info", self.ESP_GET_SECURITY_INFO, b""
)
res = struct.unpack(
"<IBBBBBBBBI", res[:16]
) # 4b flags, 1b flash_crypt_cnt, 7*1b key_purposes, 4b chip_id
self.cache["chip_id"] = res[9] # 2/4 status bytes invariant
return self.cache["chip_id"]
def get_uart_no(self):
"""
Read the UARTDEV_BUF_NO register to get the number of the currently used console
"""
if self.cache["uart_no"] is None:
self.cache["uart_no"] = self.read_reg(self.UARTDEV_BUF_NO) & 0xFF
return self.cache["uart_no"]
@classmethod
def parse_flash_size_arg(cls, arg):
try:
return cls.FLASH_SIZES[arg]
except KeyError:
raise FatalError(
"Flash size '%s' is not supported by this chip type. "
"Supported sizes: %s" % (arg, ", ".join(cls.FLASH_SIZES.keys()))
)
@classmethod
def parse_flash_freq_arg(cls, arg):
if arg is None:
# The encoding of the default flash frequency in FLASH_FREQUENCY is always 0
return 0
try:
return cls.FLASH_FREQUENCY[arg]
except KeyError:
raise FatalError(
"Flash frequency '%s' is not supported by this chip type. "
"Supported frequencies: %s"
% (arg, ", ".join(cls.FLASH_FREQUENCY.keys()))
)
def run_stub(self, stub=None):
if stub is None:
stub = StubFlasher(get_stub_json_path(self.CHIP_NAME))
if self.sync_stub_detected:
print("Stub is already running. No upload is necessary.")
return self.STUB_CLASS(self)
# Upload
print("Uploading stub...")
for field in [stub.text, stub.data]:
if field is not None:
offs = stub.text_start if field == stub.text else stub.data_start
length = len(field)
blocks = (length + self.ESP_RAM_BLOCK - 1) // self.ESP_RAM_BLOCK
self.mem_begin(length, blocks, self.ESP_RAM_BLOCK, offs)
for seq in range(blocks):
from_offs = seq * self.ESP_RAM_BLOCK
to_offs = from_offs + self.ESP_RAM_BLOCK
self.mem_block(field[from_offs:to_offs], seq)
print("Running stub...")
self.mem_finish(stub.entry)
try:
p = self.read()
except StopIteration:
raise FatalError(
"Failed to start stub. There was no response."
"\nTry increasing timeouts, for more information see: "
"https://docs.espressif.com/projects/esptool/en/latest/esptool/configuration-file.html" # noqa E501
)
if p != b"OHAI":
raise FatalError(f"Failed to start stub. Unexpected response: {p}")
print("Stub running...")
return self.STUB_CLASS(self)
@stub_and_esp32_function_only
def flash_defl_begin(self, size, compsize, offset):
"""
Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
"""
num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
erase_blocks = (size + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
t = time.time()
if self.IS_STUB:
write_size = (
size # stub expects number of bytes here, manages erasing internally
)
timeout = DEFAULT_TIMEOUT
else:
write_size = (
erase_blocks * self.FLASH_WRITE_SIZE
) # ROM expects rounded up to erase block size
timeout = timeout_per_mb(
ERASE_REGION_TIMEOUT_PER_MB, write_size
) # ROM performs the erase up front
print("Compressed %d bytes to %d..." % (size, compsize))
params = struct.pack(
"<IIII", write_size, num_blocks, self.FLASH_WRITE_SIZE, offset
)
if self.SUPPORTS_ENCRYPTED_FLASH and not self.IS_STUB:
# extra param is to enter encrypted flash mode via ROM
# (not supported currently)
params += struct.pack("<I", 0)
self.check_command(
"enter compressed flash mode",
self.ESP_FLASH_DEFL_BEGIN,
params,
timeout=timeout,
)
if size != 0 and not self.IS_STUB:
# (stub erases as it writes, but ROM loaders erase on begin)
print("Took %.2fs to erase flash block" % (time.time() - t))
return num_blocks
@stub_and_esp32_function_only
def flash_defl_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
"""Write block to flash, send compressed, retry if fail"""
for attempts_left in range(WRITE_BLOCK_ATTEMPTS - 1, -1, -1):
try:
self.check_command(
"write compressed data to flash after seq %d" % seq,
self.ESP_FLASH_DEFL_DATA,
struct.pack("<IIII", len(data), seq, 0, 0) + data,
self.checksum(data),
timeout=timeout,
)
break
except FatalError:
if attempts_left:
self.trace(
"Compressed block write failed, "
f"retrying with {attempts_left} attempts left"
)
else:
raise
@stub_and_esp32_function_only
def flash_defl_finish(self, reboot=False):
"""Leave compressed flash mode and run/reboot"""
if not reboot and not self.IS_STUB:
# skip sending flash_finish to ROM loader, as this
# exits the bootloader. Stub doesn't do this.
return
pkt = struct.pack("<I", int(not reboot))
self.check_command("leave compressed flash mode", self.ESP_FLASH_DEFL_END, pkt)
self.in_bootloader = False
@stub_and_esp32_function_only
def flash_md5sum(self, addr, size):
# the MD5 command returns additional bytes in the standard
# command reply slot
timeout = timeout_per_mb(MD5_TIMEOUT_PER_MB, size)
res = self.check_command(
"calculate md5sum",
self.ESP_SPI_FLASH_MD5,
struct.pack("<IIII", addr, size, 0, 0),
timeout=timeout,
)
if len(res) == 32:
return res.decode("utf-8") # already hex formatted
elif len(res) == 16:
return hexify(res).lower()
else:
raise FatalError("MD5Sum command returned unexpected result: %r" % res)
@stub_and_esp32_function_only
def change_baud(self, baud):
print("Changing baud rate to %d" % baud)
# stub takes the new baud rate and the old one
second_arg = self._port.baudrate if self.IS_STUB else 0
self.command(self.ESP_CHANGE_BAUDRATE, struct.pack("<II", baud, second_arg))
print("Changed.")
self._set_port_baudrate(baud)
time.sleep(0.05) # get rid of crap sent during baud rate change
self.flush_input()
@stub_function_only
def erase_flash(self):
# depending on flash chip model the erase may take this long (maybe longer!)
self.check_command(
"erase flash", self.ESP_ERASE_FLASH, timeout=CHIP_ERASE_TIMEOUT
)
@stub_function_only
def erase_region(self, offset, size):
if offset % self.FLASH_SECTOR_SIZE != 0:
raise FatalError("Offset to erase from must be a multiple of 4096")
if size % self.FLASH_SECTOR_SIZE != 0:
raise FatalError("Size of data to erase must be a multiple of 4096")
timeout = timeout_per_mb(ERASE_REGION_TIMEOUT_PER_MB, size)
self.check_command(
"erase region",
self.ESP_ERASE_REGION,
struct.pack("<II", offset, size),
timeout=timeout,
)
def read_flash_slow(self, offset, length, progress_fn):
raise NotImplementedInROMError(self, self.read_flash_slow)
def read_flash(self, offset, length, progress_fn=None):
if not self.IS_STUB:
return self.read_flash_slow(offset, length, progress_fn) # ROM-only routine
# issue a standard bootloader command to trigger the read
self.check_command(
"read flash",
self.ESP_READ_FLASH,
struct.pack("<IIII", offset, length, self.FLASH_SECTOR_SIZE, 64),
)
# now we expect (length // block_size) SLIP frames with the data
data = b""
while len(data) < length:
p = self.read()
data += p
if len(data) < length and len(p) < self.FLASH_SECTOR_SIZE:
raise FatalError(
"Corrupt data, expected 0x%x bytes but received 0x%x bytes"
% (self.FLASH_SECTOR_SIZE, len(p))
)
self.write(struct.pack("<I", len(data)))
if progress_fn and (len(data) % 1024 == 0 or len(data) == length):
progress_fn(len(data), length)
if progress_fn:
progress_fn(len(data), length)
if len(data) > length:
raise FatalError("Read more than expected")
digest_frame = self.read()
if len(digest_frame) != 16:
raise FatalError("Expected digest, got: %s" % hexify(digest_frame))
expected_digest = hexify(digest_frame).upper()
digest = hashlib.md5(data).hexdigest().upper()
if digest != expected_digest:
raise FatalError(
"Digest mismatch: expected %s, got %s" % (expected_digest, digest)
)
return data
def flash_spi_attach(self, hspi_arg):
"""Send SPI attach command to enable the SPI flash pins
ESP8266 ROM does this when you send flash_begin, ESP32 ROM
has it as a SPI command.
"""
# last 3 bytes in ESP_SPI_ATTACH argument are reserved values
arg = struct.pack("<I", hspi_arg)
if not self.IS_STUB:
# ESP32 ROM loader takes additional 'is legacy' arg, which is not
# currently supported in the stub loader or esptool.py
# (as it's not usually needed.)
is_legacy = 0
arg += struct.pack("BBBB", is_legacy, 0, 0, 0)
self.check_command("configure SPI flash pins", self.ESP_SPI_ATTACH, arg)
def flash_set_parameters(self, size):
"""Tell the ESP bootloader the parameters of the chip
Corresponds to the "flashchip" data structure that the ROM
has in RAM.
'size' is in bytes.
All other flash parameters are currently hardcoded (on ESP8266
these are mostly ignored by ROM code, on ESP32 I'm not sure.)
"""
fl_id = 0
total_size = size
block_size = 64 * 1024
sector_size = 4 * 1024
page_size = 256
status_mask = 0xFFFF
self.check_command(
"set SPI params",
self.ESP_SPI_SET_PARAMS,
struct.pack(
"<IIIIII",
fl_id,
total_size,
block_size,
sector_size,
page_size,
status_mask,
),
)
def run_spiflash_command(
self,
spiflash_command,
data=b"",
read_bits=0,
addr=None,
addr_len=0,
dummy_len=0,
):
"""Run an arbitrary SPI flash command.
This function uses the "USR_COMMAND" functionality in the ESP
SPI hardware, rather than the precanned commands supported by
hardware. So the value of spiflash_command is an actual command
byte, sent over the wire.
After writing command byte, writes 'data' to MOSI and then
reads back 'read_bits' of reply on MISO. Result is a number.
"""
# SPI_USR register flags
SPI_USR_COMMAND = 1 << 31
SPI_USR_ADDR = 1 << 30
SPI_USR_DUMMY = 1 << 29
SPI_USR_MISO = 1 << 28
SPI_USR_MOSI = 1 << 27
# SPI registers, base address differs ESP32* vs 8266
base = self.SPI_REG_BASE
SPI_CMD_REG = base + 0x00
SPI_ADDR_REG = base + 0x04
SPI_USR_REG = base + self.SPI_USR_OFFS
SPI_USR1_REG = base + self.SPI_USR1_OFFS
SPI_USR2_REG = base + self.SPI_USR2_OFFS
SPI_W0_REG = base + self.SPI_W0_OFFS
# following two registers are ESP32 and later chips only
if self.SPI_MOSI_DLEN_OFFS is not None:
# ESP32 and later chips have a more sophisticated way
# to set up "user" commands
def set_data_lengths(mosi_bits, miso_bits):
SPI_MOSI_DLEN_REG = base + self.SPI_MOSI_DLEN_OFFS
SPI_MISO_DLEN_REG = base + self.SPI_MISO_DLEN_OFFS
if mosi_bits > 0:
self.write_reg(SPI_MOSI_DLEN_REG, mosi_bits - 1)
if miso_bits > 0:
self.write_reg(SPI_MISO_DLEN_REG, miso_bits - 1)
flags = 0
if dummy_len > 0:
flags |= dummy_len - 1
if addr_len > 0:
flags |= (addr_len - 1) << SPI_USR_ADDR_LEN_SHIFT
if flags:
self.write_reg(SPI_USR1_REG, flags)
else:
def set_data_lengths(mosi_bits, miso_bits):
SPI_DATA_LEN_REG = SPI_USR1_REG
SPI_MOSI_BITLEN_S = 17
SPI_MISO_BITLEN_S = 8
mosi_mask = 0 if (mosi_bits == 0) else (mosi_bits - 1)
miso_mask = 0 if (miso_bits == 0) else (miso_bits - 1)
flags = (miso_mask << SPI_MISO_BITLEN_S) | (
mosi_mask << SPI_MOSI_BITLEN_S
)
if dummy_len > 0:
flags |= dummy_len - 1
if addr_len > 0:
flags |= (addr_len - 1) << SPI_USR_ADDR_LEN_SHIFT
self.write_reg(SPI_DATA_LEN_REG, flags)
# SPI peripheral "command" bitmasks for SPI_CMD_REG
SPI_CMD_USR = 1 << 18
# shift values
SPI_USR2_COMMAND_LEN_SHIFT = 28
SPI_USR_ADDR_LEN_SHIFT = 26
if read_bits > 32:
raise FatalError(
"Reading more than 32 bits back from a SPI flash "
"operation is unsupported"
)
if len(data) > 64:
raise FatalError(
"Writing more than 64 bytes of data with one SPI "
"command is unsupported"
)
data_bits = len(data) * 8
old_spi_usr = self.read_reg(SPI_USR_REG)
old_spi_usr2 = self.read_reg(SPI_USR2_REG)
flags = SPI_USR_COMMAND
if read_bits > 0:
flags |= SPI_USR_MISO
if data_bits > 0:
flags |= SPI_USR_MOSI
if addr_len > 0:
flags |= SPI_USR_ADDR
if dummy_len > 0:
flags |= SPI_USR_DUMMY
set_data_lengths(data_bits, read_bits)
self.write_reg(SPI_USR_REG, flags)
self.write_reg(
SPI_USR2_REG, (7 << SPI_USR2_COMMAND_LEN_SHIFT) | spiflash_command
)
if addr and addr_len > 0:
self.write_reg(SPI_ADDR_REG, addr)
if data_bits == 0:
self.write_reg(SPI_W0_REG, 0) # clear data register before we read it
else:
data = pad_to(data, 4, b"\00") # pad to 32-bit multiple
words = struct.unpack("I" * (len(data) // 4), data)
next_reg = SPI_W0_REG
for word in words:
self.write_reg(next_reg, word)
next_reg += 4
self.write_reg(SPI_CMD_REG, SPI_CMD_USR)
def wait_done():
for _ in range(10):
if (self.read_reg(SPI_CMD_REG) & SPI_CMD_USR) == 0:
return
raise FatalError("SPI command did not complete in time")
wait_done()
status = self.read_reg(SPI_W0_REG)
# restore some SPI controller registers
self.write_reg(SPI_USR_REG, old_spi_usr)
self.write_reg(SPI_USR2_REG, old_spi_usr2)
return status
def read_spiflash_sfdp(self, addr, read_bits):
CMD_RDSFDP = 0x5A
return self.run_spiflash_command(
CMD_RDSFDP, read_bits=read_bits, addr=addr, addr_len=24, dummy_len=8
)
def read_status(self, num_bytes=2):
"""Read up to 24 bits (num_bytes) of SPI flash status register contents
via RDSR, RDSR2, RDSR3 commands
Not all SPI flash supports all three commands. The upper 1 or 2
bytes may be 0xFF.
"""
SPIFLASH_RDSR = 0x05
SPIFLASH_RDSR2 = 0x35
SPIFLASH_RDSR3 = 0x15
status = 0
shift = 0
for cmd in [SPIFLASH_RDSR, SPIFLASH_RDSR2, SPIFLASH_RDSR3][0:num_bytes]:
status += self.run_spiflash_command(cmd, read_bits=8) << shift
shift += 8
return status
def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
"""Write up to 24 bits (num_bytes) of new status register
num_bytes can be 1, 2 or 3.
Not all flash supports the additional commands to write the
second and third byte of the status register. When writing 2
bytes, esptool also sends a 16-byte WRSR command (as some
flash types use this instead of WRSR2.)
If the set_non_volatile flag is set, non-volatile bits will
be set as well as volatile ones (WREN used instead of WEVSR).
"""
SPIFLASH_WRSR = 0x01
SPIFLASH_WRSR2 = 0x31
SPIFLASH_WRSR3 = 0x11
SPIFLASH_WEVSR = 0x50
SPIFLASH_WREN = 0x06
SPIFLASH_WRDI = 0x04
enable_cmd = SPIFLASH_WREN if set_non_volatile else SPIFLASH_WEVSR
# try using a 16-bit WRSR (not supported by all chips)
# this may be redundant, but shouldn't hurt
if num_bytes == 2:
self.run_spiflash_command(enable_cmd)
self.run_spiflash_command(SPIFLASH_WRSR, struct.pack("<H", new_status))
# also try using individual commands
# (also not supported by all chips for num_bytes 2 & 3)
for cmd in [SPIFLASH_WRSR, SPIFLASH_WRSR2, SPIFLASH_WRSR3][0:num_bytes]:
self.run_spiflash_command(enable_cmd)
self.run_spiflash_command(cmd, struct.pack("B", new_status & 0xFF))
new_status >>= 8
self.run_spiflash_command(SPIFLASH_WRDI)
def get_crystal_freq(self):
"""
Figure out the crystal frequency from the UART clock divider
Returns a normalized value in integer MHz (only values 40 or 26 are supported)
"""
# The logic here is:
# - We know that our baud rate and the ESP UART baud rate are roughly the same,
# or we couldn't communicate
# - We can read the UART clock divider register to know how the ESP derives this
# from the APB bus frequency
# - Multiplying these two together gives us the bus frequency which is either
# the crystal frequency (ESP32) or double the crystal frequency (ESP8266).
# See the self.XTAL_CLK_DIVIDER parameter for this factor.
uart_div = self.read_reg(self.UART_CLKDIV_REG) & self.UART_CLKDIV_MASK
est_xtal = (self._port.baudrate * uart_div) / 1e6 / self.XTAL_CLK_DIVIDER
norm_xtal = 40 if est_xtal > 33 else 26
if abs(norm_xtal - est_xtal) > 1:
print(
"WARNING: Detected crystal freq %.2fMHz is quite different to "
"normalized freq %dMHz. Unsupported crystal in use?"
% (est_xtal, norm_xtal)
)
return norm_xtal
def hard_reset(self):
print("Hard resetting via RTS pin...")
HardReset(self._port)()
def soft_reset(self, stay_in_bootloader):
if not self.IS_STUB:
if stay_in_bootloader:
return # ROM bootloader is already in bootloader!
else:
# 'run user code' is as close to a soft reset as we can do
self.flash_begin(0, 0)
self.flash_finish(False)
else:
if stay_in_bootloader:
# soft resetting from the stub loader
# will re-load the ROM bootloader
self.flash_begin(0, 0)
self.flash_finish(True)
elif self.CHIP_NAME != "ESP8266":
raise FatalError(
"Soft resetting is currently only supported on ESP8266"
)
else:
# running user code from stub loader requires some hacks
# in the stub loader
self.command(self.ESP_RUN_USER_CODE, wait_response=False)
def check_chip_id(self):
try:
chip_id = self.get_chip_id()
if chip_id != self.IMAGE_CHIP_ID:
print(
"WARNING: Chip ID {} ({}) doesn't match expected Chip ID {}. "
"esptool may not work correctly.".format(
chip_id,
self.UNSUPPORTED_CHIPS.get(chip_id, "Unknown"),
self.IMAGE_CHIP_ID,
)
)
# Try to flash anyways by disabling stub
self.stub_is_disabled = True
except NotImplementedInROMError:
pass
def slip_reader(port, trace_function):
"""Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems.
"""
def detect_panic_handler(input):
"""
Checks the input bytes for panic handler messages.
Raises a FatalError if Guru Meditation or Fatal Exception is found, as both
of these are used between different ROM versions.
Tries to also parse the error cause (e.g. IllegalInstruction).
"""
guru_meditation = (
rb"G?uru Meditation Error: (?:Core \d panic'ed \(([a-zA-Z ]*)\))?"
)
fatal_exception = rb"F?atal exception \(\d+\): (?:([a-zA-Z ]*)?.*epc)?"
# Search either for Guru Meditation or Fatal Exception
data = re.search(
rb"".join([rb"(?:", guru_meditation, rb"|", fatal_exception, rb")"]),
input,
re.DOTALL,
)
if data is not None:
cause = [
"({})".format(i.decode("utf-8"))
for i in [data.group(1), data.group(2)]
if i is not None
]
cause = f" {cause[0]}" if len(cause) else ""
msg = f"Guru Meditation Error detected{cause}"
raise FatalError(msg)
partial_packet = None
in_escape = False
successful_slip = False
while True:
waiting = port.inWaiting()
read_bytes = port.read(1 if waiting == 0 else waiting)
if read_bytes == b"":
if partial_packet is None: # fail due to no data
msg = (
"Serial data stream stopped: Possible serial noise or corruption."
if successful_slip
else "No serial data received."
)
else: # fail during packet transfer
msg = "Packet content transfer stopped (received {} bytes)".format(
len(partial_packet)
)
trace_function(msg)
raise FatalError(msg)
trace_function("Read %d bytes: %s", len(read_bytes), HexFormatter(read_bytes))
for b in read_bytes:
b = bytes([b])
if partial_packet is None: # waiting for packet header
if b == b"\xc0":
partial_packet = b""
else:
trace_function("Read invalid data: %s", HexFormatter(read_bytes))
remaining_data = port.read(port.inWaiting())
trace_function(
"Remaining data in serial buffer: %s",
HexFormatter(remaining_data),
)
detect_panic_handler(read_bytes + remaining_data)
raise FatalError(
"Invalid head of packet (0x%s): "
"Possible serial noise or corruption." % hexify(b)
)
elif in_escape: # part-way through escape sequence
in_escape = False
if b == b"\xdc":
partial_packet += b"\xc0"
elif b == b"\xdd":
partial_packet += b"\xdb"
else:
trace_function("Read invalid data: %s", HexFormatter(read_bytes))
remaining_data = port.read(port.inWaiting())
trace_function(
"Remaining data in serial buffer: %s",
HexFormatter(remaining_data),
)
detect_panic_handler(read_bytes + remaining_data)
raise FatalError("Invalid SLIP escape (0xdb, 0x%s)" % (hexify(b)))
elif b == b"\xdb": # start of escape sequence
in_escape = True
elif b == b"\xc0": # end of packet
trace_function("Received full packet: %s", HexFormatter(partial_packet))
yield partial_packet
partial_packet = None
successful_slip = True
else: # normal byte in packet
partial_packet += b
class HexFormatter(object):
"""
Wrapper class which takes binary data in its constructor
and returns a hex string as it's __str__ method.
This is intended for "lazy formatting" of trace() output
in hex format. Avoids overhead (significant on slow computers)
of generating long hex strings even if tracing is disabled.
Note that this doesn't save any overhead if passed as an
argument to "%", only when passed to trace()
If auto_split is set (default), any long line (> 16 bytes) will be
printed as separately indented lines, with ASCII decoding at the end
of each line.
"""
def __init__(self, binary_string, auto_split=True):
self._s = binary_string
self._auto_split = auto_split
def __str__(self):
if self._auto_split and len(self._s) > 16:
result = ""
s = self._s
while len(s) > 0:
line = s[:16]
ascii_line = "".join(
c
if (
c == " "
or (c in string.printable and c not in string.whitespace)
)
else "."
for c in line.decode("ascii", "replace")
)
s = s[16:]
result += "\n %-16s %-16s | %s" % (
hexify(line[:8], False),
hexify(line[8:], False),
ascii_line,
)
return result
else:
return hexify(self._s, False)
| 60,941 | Python | .py | 1,405 | 31.984342 | 116 | 0.573459 | OLIMEX/RVPC | 8 | 2 | 1 | GPL-3.0 | 9/5/2024, 10:48:43 PM (Europe/Amsterdam) |
2,289,606 | __init__.py | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/__init__.py | # SPDX-FileCopyrightText: 2014-2022 Fredrik Ahlberg, Angus Gratton,
# Espressif Systems (Shanghai) CO LTD, other contributors as noted.
#
# SPDX-License-Identifier: GPL-2.0-or-later
__all__ = [
"chip_id",
"detect_chip",
"dump_mem",
"elf2image",
"erase_flash",
"erase_region",
"flash_id",
"get_security_info",
"image_info",
"load_ram",
"make_image",
"merge_bin",
"read_flash",
"read_flash_status",
"read_mac",
"read_mem",
"run",
"verify_flash",
"version",
"write_flash",
"write_flash_status",
"write_mem",
]
__version__ = "4.7-dev"
import argparse
import inspect
import os
import shlex
import sys
import time
import traceback
from esptool.cmds import (
DETECTED_FLASH_SIZES,
chip_id,
detect_chip,
detect_flash_size,
dump_mem,
elf2image,
erase_flash,
erase_region,
flash_id,
get_security_info,
image_info,
load_ram,
make_image,
merge_bin,
read_flash,
read_flash_status,
read_mac,
read_mem,
run,
verify_flash,
version,
write_flash,
write_flash_status,
write_mem,
)
from esptool.config import load_config_file
from esptool.loader import DEFAULT_CONNECT_ATTEMPTS, ESPLoader, list_ports
from esptool.targets import CHIP_DEFS, CHIP_LIST, ESP32ROM
from esptool.util import (
FatalError,
NotImplementedInROMError,
flash_size_bytes,
strip_chip_name,
)
import serial
def main(argv=None, esp=None):
"""
Main function for esptool
argv - Optional override for default arguments parsing (that uses sys.argv),
can be a list of custom arguments as strings. Arguments and their values
need to be added as individual items to the list
e.g. "-b 115200" thus becomes ['-b', '115200'].
esp - Optional override of the connected device previously
returned by get_default_connected_device()
"""
external_esp = esp is not None
parser = argparse.ArgumentParser(
description="esptool.py v%s - Espressif chips ROM Bootloader Utility"
% __version__,
prog="esptool",
)
parser.add_argument(
"--chip",
"-c",
help="Target chip type",
type=strip_chip_name,
choices=["auto"] + CHIP_LIST,
default=os.environ.get("ESPTOOL_CHIP", "auto"),
)
parser.add_argument(
"--port",
"-p",
help="Serial port device",
default=os.environ.get("ESPTOOL_PORT", None),
)
parser.add_argument(
"--baud",
"-b",
help="Serial port baud rate used when flashing/reading",
type=arg_auto_int,
default=os.environ.get("ESPTOOL_BAUD", ESPLoader.ESP_ROM_BAUD),
)
parser.add_argument(
"--before",
help="What to do before connecting to the chip",
choices=["default_reset", "usb_reset", "no_reset", "no_reset_no_sync"],
default=os.environ.get("ESPTOOL_BEFORE", "default_reset"),
)
parser.add_argument(
"--after",
"-a",
help="What to do after esptool.py is finished",
choices=["hard_reset", "soft_reset", "no_reset", "no_reset_stub"],
default=os.environ.get("ESPTOOL_AFTER", "hard_reset"),
)
parser.add_argument(
"--no-stub",
help="Disable launching the flasher stub, only talk to ROM bootloader. "
"Some features will not be available.",
action="store_true",
)
parser.add_argument(
"--trace",
"-t",
help="Enable trace-level output of esptool.py interactions.",
action="store_true",
)
parser.add_argument(
"--override-vddsdio",
help="Override ESP32 VDDSDIO internal voltage regulator (use with care)",
choices=ESP32ROM.OVERRIDE_VDDSDIO_CHOICES,
nargs="?",
)
parser.add_argument(
"--connect-attempts",
help=(
"Number of attempts to connect, negative or 0 for infinite. "
"Default: %d." % DEFAULT_CONNECT_ATTEMPTS
),
type=int,
default=os.environ.get("ESPTOOL_CONNECT_ATTEMPTS", DEFAULT_CONNECT_ATTEMPTS),
)
subparsers = parser.add_subparsers(
dest="operation", help="Run esptool.py {command} -h for additional help"
)
def add_spi_connection_arg(parent):
parent.add_argument(
"--spi-connection",
"-sc",
help="ESP32-only argument. Override default SPI Flash connection. "
"Value can be SPI, HSPI or a comma-separated list of 5 I/O numbers "
"to use for SPI flash (CLK,Q,D,HD,CS).",
action=SpiConnectionAction,
)
parser_load_ram = subparsers.add_parser(
"load_ram", help="Download an image to RAM and execute"
)
parser_load_ram.add_argument("filename", help="Firmware image")
parser_dump_mem = subparsers.add_parser(
"dump_mem", help="Dump arbitrary memory to disk"
)
parser_dump_mem.add_argument("address", help="Base address", type=arg_auto_int)
parser_dump_mem.add_argument(
"size", help="Size of region to dump", type=arg_auto_int
)
parser_dump_mem.add_argument("filename", help="Name of binary dump")
parser_read_mem = subparsers.add_parser(
"read_mem", help="Read arbitrary memory location"
)
parser_read_mem.add_argument("address", help="Address to read", type=arg_auto_int)
parser_write_mem = subparsers.add_parser(
"write_mem", help="Read-modify-write to arbitrary memory location"
)
parser_write_mem.add_argument("address", help="Address to write", type=arg_auto_int)
parser_write_mem.add_argument("value", help="Value", type=arg_auto_int)
parser_write_mem.add_argument(
"mask",
help="Mask of bits to write",
type=arg_auto_int,
nargs="?",
default="0xFFFFFFFF",
)
def add_spi_flash_subparsers(parent, allow_keep, auto_detect):
"""Add common parser arguments for SPI flash properties"""
extra_keep_args = ["keep"] if allow_keep else []
if auto_detect and allow_keep:
extra_fs_message = ", detect, or keep"
flash_sizes = ["detect", "keep"]
elif auto_detect:
extra_fs_message = ", or detect"
flash_sizes = ["detect"]
elif allow_keep:
extra_fs_message = ", or keep"
flash_sizes = ["keep"]
else:
extra_fs_message = ""
flash_sizes = []
parent.add_argument(
"--flash_freq",
"-ff",
help="SPI Flash frequency",
choices=extra_keep_args
+ [
"80m",
"60m",
"48m",
"40m",
"30m",
"26m",
"24m",
"20m",
"16m",
"15m",
"12m",
],
default=os.environ.get("ESPTOOL_FF", "keep" if allow_keep else None),
)
parent.add_argument(
"--flash_mode",
"-fm",
help="SPI Flash mode",
choices=extra_keep_args + ["qio", "qout", "dio", "dout"],
default=os.environ.get("ESPTOOL_FM", "keep" if allow_keep else "qio"),
)
parent.add_argument(
"--flash_size",
"-fs",
help="SPI Flash size in MegaBytes "
"(1MB, 2MB, 4MB, 8MB, 16MB, 32MB, 64MB, 128MB) "
"plus ESP8266-only (256KB, 512KB, 2MB-c1, 4MB-c1)" + extra_fs_message,
choices=flash_sizes
+ [
"256KB",
"512KB",
"1MB",
"2MB",
"2MB-c1",
"4MB",
"4MB-c1",
"8MB",
"16MB",
"32MB",
"64MB",
"128MB",
],
default=os.environ.get("ESPTOOL_FS", "keep" if allow_keep else "1MB"),
)
add_spi_connection_arg(parent)
parser_write_flash = subparsers.add_parser(
"write_flash", help="Write a binary blob to flash"
)
parser_write_flash.add_argument(
"addr_filename",
metavar="<address> <filename>",
help="Address followed by binary filename, separated by space",
action=AddrFilenamePairAction,
)
parser_write_flash.add_argument(
"--erase-all",
"-e",
help="Erase all regions of flash (not just write areas) before programming",
action="store_true",
)
add_spi_flash_subparsers(parser_write_flash, allow_keep=True, auto_detect=True)
parser_write_flash.add_argument(
"--no-progress", "-p", help="Suppress progress output", action="store_true"
)
parser_write_flash.add_argument(
"--verify",
help="Verify just-written data on flash "
"(mostly superfluous, data is read back during flashing)",
action="store_true",
)
parser_write_flash.add_argument(
"--encrypt",
help="Apply flash encryption when writing data "
"(required correct efuse settings)",
action="store_true",
)
# In order to not break backward compatibility,
# our list of encrypted files to flash is a new parameter
parser_write_flash.add_argument(
"--encrypt-files",
metavar="<address> <filename>",
help="Files to be encrypted on the flash. "
"Address followed by binary filename, separated by space.",
action=AddrFilenamePairAction,
)
parser_write_flash.add_argument(
"--ignore-flash-encryption-efuse-setting",
help="Ignore flash encryption efuse settings ",
action="store_true",
)
parser_write_flash.add_argument(
"--force",
help="Force write, skip security and compatibility checks. Use with caution!",
action="store_true",
)
compress_args = parser_write_flash.add_mutually_exclusive_group(required=False)
compress_args.add_argument(
"--compress",
"-z",
help="Compress data in transfer (default unless --no-stub is specified)",
action="store_true",
default=None,
)
compress_args.add_argument(
"--no-compress",
"-u",
help="Disable data compression during transfer "
"(default if --no-stub is specified)",
action="store_true",
)
subparsers.add_parser("run", help="Run application code in flash")
parser_image_info = subparsers.add_parser(
"image_info", help="Dump headers from a binary file (bootloader or application)"
)
parser_image_info.add_argument("filename", help="Image file to parse")
parser_image_info.add_argument(
"--version",
"-v",
help="Output format version (1 - legacy, 2 - extended)",
choices=["1", "2"],
default="1",
)
parser_make_image = subparsers.add_parser(
"make_image", help="Create an application image from binary files"
)
parser_make_image.add_argument("output", help="Output image file")
parser_make_image.add_argument(
"--segfile", "-f", action="append", help="Segment input file"
)
parser_make_image.add_argument(
"--segaddr",
"-a",
action="append",
help="Segment base address",
type=arg_auto_int,
)
parser_make_image.add_argument(
"--entrypoint",
"-e",
help="Address of entry point",
type=arg_auto_int,
default=0,
)
parser_elf2image = subparsers.add_parser(
"elf2image", help="Create an application image from ELF file"
)
parser_elf2image.add_argument("input", help="Input ELF file")
parser_elf2image.add_argument(
"--output",
"-o",
help="Output filename prefix (for version 1 image), "
"or filename (for version 2 single image)",
type=str,
)
parser_elf2image.add_argument(
"--version",
"-e",
help="Output image version",
choices=["1", "2", "3"],
default="1",
)
parser_elf2image.add_argument(
# it kept for compatibility
# Minimum chip revision (deprecated, consider using --min-rev-full)
"--min-rev",
"-r",
help=argparse.SUPPRESS,
type=int,
choices=range(256),
metavar="{0, ... 255}",
default=0,
)
parser_elf2image.add_argument(
"--min-rev-full",
help="Minimal chip revision (in format: major * 100 + minor)",
type=int,
choices=range(65536),
metavar="{0, ... 65535}",
default=0,
)
parser_elf2image.add_argument(
"--max-rev-full",
help="Maximal chip revision (in format: major * 100 + minor)",
type=int,
choices=range(65536),
metavar="{0, ... 65535}",
default=65535,
)
parser_elf2image.add_argument(
"--secure-pad",
action="store_true",
help="Pad image so once signed it will end on a 64KB boundary. "
"For Secure Boot v1 images only.",
)
parser_elf2image.add_argument(
"--secure-pad-v2",
action="store_true",
help="Pad image to 64KB, so once signed its signature sector will"
"start at the next 64K block. For Secure Boot v2 images only.",
)
parser_elf2image.add_argument(
"--elf-sha256-offset",
help="If set, insert SHA256 hash (32 bytes) of the input ELF file "
"at specified offset in the binary.",
type=arg_auto_int,
default=None,
)
parser_elf2image.add_argument(
"--dont-append-digest",
dest="append_digest",
help="Don't append a SHA256 digest of the entire image after the checksum. "
"This argument is not supported and ignored for ESP8266.",
action="store_false",
default=True,
)
parser_elf2image.add_argument(
"--use_segments",
help="If set, ELF segments will be used instead of ELF sections "
"to genereate the image.",
action="store_true",
)
parser_elf2image.add_argument(
"--flash-mmu-page-size",
help="Change flash MMU page size.",
choices=["64KB", "32KB", "16KB", "8KB"],
)
parser_elf2image.add_argument(
"--pad-to-size",
help="The block size with which the final binary image after padding "
"must be aligned to. Value 0xFF is used for padding, similar to erase_flash",
default=None,
)
add_spi_flash_subparsers(parser_elf2image, allow_keep=False, auto_detect=False)
subparsers.add_parser("read_mac", help="Read MAC address from OTP ROM")
subparsers.add_parser("chip_id", help="Read Chip ID from OTP ROM")
parser_flash_id = subparsers.add_parser(
"flash_id", help="Read SPI flash manufacturer and device ID"
)
add_spi_connection_arg(parser_flash_id)
parser_read_status = subparsers.add_parser(
"read_flash_status", help="Read SPI flash status register"
)
add_spi_connection_arg(parser_read_status)
parser_read_status.add_argument(
"--bytes",
help="Number of bytes to read (1-3)",
type=int,
choices=[1, 2, 3],
default=2,
)
parser_write_status = subparsers.add_parser(
"write_flash_status", help="Write SPI flash status register"
)
add_spi_connection_arg(parser_write_status)
parser_write_status.add_argument(
"--non-volatile",
help="Write non-volatile bits (use with caution)",
action="store_true",
)
parser_write_status.add_argument(
"--bytes",
help="Number of status bytes to write (1-3)",
type=int,
choices=[1, 2, 3],
default=2,
)
parser_write_status.add_argument("value", help="New value", type=arg_auto_int)
parser_read_flash = subparsers.add_parser(
"read_flash", help="Read SPI flash content"
)
add_spi_connection_arg(parser_read_flash)
parser_read_flash.add_argument("address", help="Start address", type=arg_auto_int)
parser_read_flash.add_argument(
"size",
help="Size of region to dump. Use `ALL` to read to the end of flash.",
type=arg_auto_size,
)
parser_read_flash.add_argument("filename", help="Name of binary dump")
parser_read_flash.add_argument(
"--no-progress", "-p", help="Suppress progress output", action="store_true"
)
parser_verify_flash = subparsers.add_parser(
"verify_flash", help="Verify a binary blob against flash"
)
parser_verify_flash.add_argument(
"addr_filename",
help="Address and binary file to verify there, separated by space",
action=AddrFilenamePairAction,
)
parser_verify_flash.add_argument(
"--diff", "-d", help="Show differences", choices=["no", "yes"], default="no"
)
add_spi_flash_subparsers(parser_verify_flash, allow_keep=True, auto_detect=True)
parser_erase_flash = subparsers.add_parser(
"erase_flash", help="Perform Chip Erase on SPI flash"
)
parser_erase_flash.add_argument(
"--force",
help="Erase flash even if security features are enabled. Use with caution!",
action="store_true",
)
add_spi_connection_arg(parser_erase_flash)
parser_erase_region = subparsers.add_parser(
"erase_region", help="Erase a region of the flash"
)
parser_erase_region.add_argument(
"--force",
help="Erase region even if security features are enabled. Use with caution!",
action="store_true",
)
add_spi_connection_arg(parser_erase_region)
parser_erase_region.add_argument(
"address", help="Start address (must be multiple of 4096)", type=arg_auto_int
)
parser_erase_region.add_argument(
"size",
help="Size of region to erase (must be multiple of 4096). "
"Use `ALL` to erase to the end of flash.",
type=arg_auto_size,
)
parser_merge_bin = subparsers.add_parser(
"merge_bin",
help="Merge multiple raw binary files into a single file for later flashing",
)
parser_merge_bin.add_argument(
"--output", "-o", help="Output filename", type=str, required=True
)
parser_merge_bin.add_argument(
"--format", "-f", help="Format of the output file", choices="raw", default="raw"
) # for future expansion
add_spi_flash_subparsers(parser_merge_bin, allow_keep=True, auto_detect=False)
parser_merge_bin.add_argument(
"--target-offset",
"-t",
help="Target offset where the output file will be flashed",
type=arg_auto_int,
default=0,
)
parser_merge_bin.add_argument(
"--fill-flash-size",
help="If set, the final binary file will be padded with FF "
"bytes up to this flash size.",
choices=[
"256KB",
"512KB",
"1MB",
"2MB",
"4MB",
"8MB",
"16MB",
"32MB",
"64MB",
"128MB",
],
)
parser_merge_bin.add_argument(
"addr_filename",
metavar="<address> <filename>",
help="Address followed by binary filename, separated by space",
action=AddrFilenamePairAction,
)
subparsers.add_parser("get_security_info", help="Get some security-related data")
subparsers.add_parser("version", help="Print esptool version")
# internal sanity check - every operation matches a module function of the same name
for operation in subparsers.choices.keys():
assert operation in globals(), "%s should be a module function" % operation
argv = expand_file_arguments(argv or sys.argv[1:])
args = parser.parse_args(argv)
print("esptool.py v%s" % __version__)
load_config_file(verbose=True)
# operation function can take 1 arg (args), 2 args (esp, arg)
# or be a member function of the ESPLoader class.
if args.operation is None:
parser.print_help()
sys.exit(1)
# Forbid the usage of both --encrypt, which means encrypt all the given files,
# and --encrypt-files, which represents the list of files to encrypt.
# The reason is that allowing both at the same time increases the chances of
# having contradictory lists (e.g. one file not available in one of list).
if (
args.operation == "write_flash"
and args.encrypt
and args.encrypt_files is not None
):
raise FatalError(
"Options --encrypt and --encrypt-files "
"must not be specified at the same time."
)
operation_func = globals()[args.operation]
operation_args = inspect.getfullargspec(operation_func).args
if (
operation_args[0] == "esp"
): # operation function takes an ESPLoader connection object
if args.before != "no_reset_no_sync":
initial_baud = min(
ESPLoader.ESP_ROM_BAUD, args.baud
) # don't sync faster than the default baud rate
else:
initial_baud = args.baud
if args.port is None:
ser_list = get_port_list()
print("Found %d serial ports" % len(ser_list))
else:
ser_list = [args.port]
esp = esp or get_default_connected_device(
ser_list,
port=args.port,
connect_attempts=args.connect_attempts,
initial_baud=initial_baud,
chip=args.chip,
trace=args.trace,
before=args.before,
)
if esp is None:
raise FatalError(
"Could not connect to an Espressif device "
"on any of the %d available serial ports." % len(ser_list)
)
if esp.secure_download_mode:
print("Chip is %s in Secure Download Mode" % esp.CHIP_NAME)
else:
print("Chip is %s" % (esp.get_chip_description()))
print("Features: %s" % ", ".join(esp.get_chip_features()))
print("Crystal is %dMHz" % esp.get_crystal_freq())
read_mac(esp, args)
if not args.no_stub:
if esp.secure_download_mode:
print(
"WARNING: Stub loader is not supported in Secure Download Mode, "
"setting --no-stub"
)
args.no_stub = True
elif not esp.IS_STUB and esp.stub_is_disabled:
print(
"WARNING: Stub loader has been disabled for compatibility, "
"setting --no-stub"
)
args.no_stub = True
else:
try:
esp = esp.run_stub()
except Exception:
# The CH9102 bridge (PID: 0x55D4) can have issues on MacOS
if sys.platform == "darwin" and esp._get_pid() == 0x55D4:
print(
"\nNote: If issues persist, "
"try installing the WCH USB-to-Serial MacOS driver."
)
raise
if args.override_vddsdio:
esp.override_vddsdio(args.override_vddsdio)
if args.baud > initial_baud:
try:
esp.change_baud(args.baud)
except NotImplementedInROMError:
print(
"WARNING: ROM doesn't support changing baud rate. "
"Keeping initial baud rate %d" % initial_baud
)
# override common SPI flash parameter stuff if configured to do so
if hasattr(args, "spi_connection") and args.spi_connection is not None:
if esp.CHIP_NAME != "ESP32":
raise FatalError(
"Chip %s does not support --spi-connection option." % esp.CHIP_NAME
)
print("Configuring SPI flash mode...")
esp.flash_spi_attach(args.spi_connection)
elif args.no_stub:
print("Enabling default SPI flash mode...")
# ROM loader doesn't enable flash unless we explicitly do it
esp.flash_spi_attach(0)
# XMC chip startup sequence
XMC_VENDOR_ID = 0x20
def is_xmc_chip_strict():
id = esp.flash_id()
rdid = ((id & 0xFF) << 16) | ((id >> 16) & 0xFF) | (id & 0xFF00)
vendor_id = (rdid >> 16) & 0xFF
mfid = (rdid >> 8) & 0xFF
cpid = rdid & 0xFF
if vendor_id != XMC_VENDOR_ID:
return False
matched = False
if mfid == 0x40:
if cpid >= 0x13 and cpid <= 0x20:
matched = True
elif mfid == 0x41:
if cpid >= 0x17 and cpid <= 0x20:
matched = True
elif mfid == 0x50:
if cpid >= 0x15 and cpid <= 0x16:
matched = True
return matched
def flash_xmc_startup():
# If the RDID value is a valid XMC one, may skip the flow
fast_check = True
if fast_check and is_xmc_chip_strict():
return # Successful XMC flash chip boot-up detected by RDID, skipping.
sfdp_mfid_addr = 0x10
mf_id = esp.read_spiflash_sfdp(sfdp_mfid_addr, 8)
if mf_id != XMC_VENDOR_ID: # Non-XMC chip detected by SFDP Read, skipping.
return
print(
"WARNING: XMC flash chip boot-up failure detected! "
"Running XMC25QHxxC startup flow"
)
esp.run_spiflash_command(0xB9) # Enter DPD
esp.run_spiflash_command(0x79) # Enter UDPD
esp.run_spiflash_command(0xFF) # Exit UDPD
time.sleep(0.002) # Delay tXUDPD
esp.run_spiflash_command(0xAB) # Release Power-Down
time.sleep(0.00002)
# Check for success
if not is_xmc_chip_strict():
print("WARNING: XMC flash boot-up fix failed.")
print("XMC flash chip boot-up fix successful!")
# Check flash chip connection
if not esp.secure_download_mode:
try:
flash_id = esp.flash_id()
if flash_id in (0xFFFFFF, 0x000000):
print(
"WARNING: Failed to communicate with the flash chip, "
"read/write operations will fail. "
"Try checking the chip connections or removing "
"any other hardware connected to IOs."
)
except FatalError as e:
raise FatalError(f"Unable to verify flash chip connection ({e}).")
# Check if XMC SPI flash chip booted-up successfully, fix if not
if not esp.secure_download_mode:
try:
flash_xmc_startup()
except FatalError as e:
esp.trace(f"Unable to perform XMC flash chip startup sequence ({e}).")
if hasattr(args, "flash_size"):
print("Configuring flash size...")
if args.flash_size == "detect":
flash_size = detect_flash_size(esp, args)
elif args.flash_size == "keep":
flash_size = detect_flash_size(esp, args=None)
else:
flash_size = args.flash_size
if flash_size is not None: # Secure download mode
esp.flash_set_parameters(flash_size_bytes(flash_size))
# Check if stub supports chosen flash size
if esp.IS_STUB and flash_size in ("32MB", "64MB", "128MB"):
print(
"WARNING: Flasher stub doesn't fully support flash size larger "
"than 16MB, in case of failure use --no-stub."
)
if getattr(args, "size", "") == "all":
if esp.secure_download_mode:
raise FatalError(
"Detecting flash size is not supported in secure download mode. "
"Set an exact size value."
)
# detect flash size
flash_id = esp.flash_id()
size_id = flash_id >> 16
size_str = DETECTED_FLASH_SIZES.get(size_id)
if size_str is None:
raise FatalError(
"Detecting flash size failed. Set an exact size value."
)
print(f"Detected flash size: {size_str}")
args.size = flash_size_bytes(size_str)
if esp.IS_STUB and hasattr(args, "address") and hasattr(args, "size"):
if args.address + args.size > 0x1000000:
print(
"WARNING: Flasher stub doesn't fully support flash size larger "
"than 16MB, in case of failure use --no-stub."
)
try:
operation_func(esp, args)
finally:
try: # Clean up AddrFilenamePairAction files
for address, argfile in args.addr_filename:
argfile.close()
except AttributeError:
pass
# Handle post-operation behaviour (reset or other)
if operation_func == load_ram:
# the ESP is now running the loaded image, so let it run
print("Exiting immediately.")
elif args.after == "hard_reset":
esp.hard_reset()
elif args.after == "soft_reset":
print("Soft resetting...")
# flash_finish will trigger a soft reset
esp.soft_reset(False)
elif args.after == "no_reset_stub":
print("Staying in flasher stub.")
else: # args.after == 'no_reset'
print("Staying in bootloader.")
if esp.IS_STUB:
esp.soft_reset(True) # exit stub back to ROM loader
if not external_esp:
esp._port.close()
else:
operation_func(args)
def arg_auto_int(x):
return int(x, 0)
def arg_auto_size(x):
x = x.lower()
return x if x == "all" else arg_auto_int(x)
def get_port_list():
if list_ports is None:
raise FatalError(
"Listing all serial ports is currently not available. "
"Please try to specify the port when running esptool.py or update "
"the pyserial package to the latest version"
)
return sorted(ports.device for ports in list_ports.comports())
def expand_file_arguments(argv):
"""
Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order
on the command line.
"""
new_args = []
expanded = False
for arg in argv:
if arg.startswith("@"):
expanded = True
with open(arg[1:], "r") as f:
for line in f.readlines():
new_args += shlex.split(line)
else:
new_args.append(arg)
if expanded:
print(f"esptool.py {' '.join(new_args)}")
return new_args
return argv
def get_default_connected_device(
serial_list,
port,
connect_attempts,
initial_baud,
chip="auto",
trace=False,
before="default_reset",
):
_esp = None
for each_port in reversed(serial_list):
print("Serial port %s" % 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
print("%s failed to connect: %s" % (each_port, err))
if _esp and _esp._port:
_esp._port.close()
_esp = None
return _esp
class SpiConnectionAction(argparse.Action):
"""
Custom action to parse 'spi connection' override.
Values are SPI, HSPI, or a sequence of 5 pin numbers separated by commas.
"""
def __call__(self, parser, namespace, value, option_string=None):
if value.upper() == "SPI":
value = 0
elif value.upper() == "HSPI":
value = 1
elif "," in value:
values = value.split(",")
if len(values) != 5:
raise argparse.ArgumentError(
self,
"%s is not a valid list of comma-separate pin numbers. "
"Must be 5 numbers - CLK,Q,D,HD,CS." % value,
)
try:
values = tuple(int(v, 0) for v in values)
except ValueError:
raise argparse.ArgumentError(
self,
"%s is not a valid argument. All pins must be numeric values"
% values,
)
if any([v for v in values if v > 33 or v < 0]):
raise argparse.ArgumentError(
self, "Pin numbers must be in the range 0-33."
)
# encode the pin numbers as a 32-bit integer with packed 6-bit values,
# the same way ESP32 ROM takes them
# TODO: make this less ESP32 ROM specific somehow...
clk, q, d, hd, cs = values
value = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk
else:
raise argparse.ArgumentError(
self,
"%s is not a valid spi-connection value. "
"Values are SPI, HSPI, or a sequence of 5 pin numbers CLK,Q,D,HD,CS)."
% value,
)
setattr(namespace, self.dest, value)
class AddrFilenamePairAction(argparse.Action):
"""Custom parser class for the address/filename pairs passed as arguments"""
def __init__(self, option_strings, dest, nargs="+", **kwargs):
super(AddrFilenamePairAction, self).__init__(
option_strings, dest, nargs, **kwargs
)
def __call__(self, parser, namespace, values, option_string=None):
# validate pair arguments
pairs = []
for i in range(0, len(values), 2):
try:
address = int(values[i], 0)
except ValueError:
raise argparse.ArgumentError(
self, 'Address "%s" must be a number' % values[i]
)
try:
argfile = open(values[i + 1], "rb")
except IOError as e:
raise argparse.ArgumentError(self, e)
except IndexError:
raise argparse.ArgumentError(
self,
"Must be pairs of an address "
"and the binary filename to write there",
)
pairs.append((address, argfile))
# Sort the addresses and check for overlapping
end = 0
for address, argfile in sorted(pairs, key=lambda x: x[0]):
argfile.seek(0, 2) # seek to end
size = argfile.tell()
argfile.seek(0)
sector_start = address & ~(ESPLoader.FLASH_SECTOR_SIZE - 1)
sector_end = (
(address + size + ESPLoader.FLASH_SECTOR_SIZE - 1)
& ~(ESPLoader.FLASH_SECTOR_SIZE - 1)
) - 1
if sector_start < end:
message = "Detected overlap at address: 0x%x for file: %s" % (
address,
argfile.name,
)
raise argparse.ArgumentError(self, message)
end = sector_end
setattr(namespace, self.dest, pairs)
def _main():
try:
main()
except FatalError as e:
print(f"\nA fatal error occurred: {e}")
sys.exit(2)
except serial.serialutil.SerialException as e:
print(f"\nA serial exception error occurred: {e}")
print(
"Note: This error originates from pySerial. "
"It is likely not a problem with esptool, "
"but with the hardware connection or drivers."
)
print(
"For troubleshooting steps visit: "
"https://docs.espressif.com/projects/esptool/en/latest/troubleshooting.html"
)
sys.exit(1)
except StopIteration:
print(traceback.format_exc())
print("A fatal error occurred: The chip stopped responding.")
sys.exit(2)
if __name__ == "__main__":
_main()
| 36,819 | Python | .py | 987 | 27.443769 | 88 | 0.570165 | OLIMEX/RVPC | 8 | 2 | 1 | GPL-3.0 | 9/5/2024, 10:48:43 PM (Europe/Amsterdam) |
2,289,607 | config.cpython-310.pyc | OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/__pycache__/config.cpython-310.pyc | o
’jÂd" ã @ s: d dl Z d dlZg d¢Zd
dd„Zd
dd„Zd
dd „ZdS )é N)
ÚtimeoutÚchip_erase_timeoutÚmax_timeoutÚsync_timeoutÚmd5_timeout_per_mbÚerase_region_timeout_per_mbÚerase_write_timeout_per_mbÚmem_end_rom_timeoutÚserial_write_timeoutÚconnect_attemptsÚwrite_block_attemptsÚreset_delayÚcustom_reset_sequenceFc
C sì t j | ¡sdS t ¡ }z@|j| dd� | d¡rJ|rGtt| d¡ƒtt
ƒ ƒ}| ¡ t|ƒ}|dkrG|dkr:dnd}t
d |d
|¡¡ƒ W dS W dS ttjfyu } z|rjt
d| › d
|› �ƒ W Y d }~dS W Y d }~dS d }~ww )NFzUTF-8)ÚencodingÚesptoolr é ÚsÚ z)Ignoring unknown config file option{}: {}z, TzIgnoring invalid config file z: )ÚosÚpathÚexistsÚconfigparserÚRawConfigParserÚreadÚhas_sectionÚlistÚsetÚoptionsÚCONFIG_OPTIONSÚsortÚlenÚprintÚformatÚjoinÚUnicodeDecodeErrorÚError)Ú file_pathÚverboseÚcfgÚunknown_optsÚno_of_unknown_optsÚsuffixÚe© r- ú./home/ceco/Downloads/esptool/esptool/config.pyÚ_validate_config_file s8
ÿÿôı
ş€ır/ c C s. dD ]}t j | |¡}t||ƒr| S qd S )N)zesptool.cfgz setup.cfgztox.ini)r r r# r/ )Údir_pathr' Ú candidateÚcfg_pathr- r- r. Ú_find_config_file5 s
ÿr3 c C sÎ d}t j d¡}|d urt|ƒr|}d}n(t j d¡}t jdkr%|› d�n|› d�}t ¡ ||fD ]}t|| ƒ}|r< nq1t
¡ }i |d< |