增加脱机烧录功能

This commit is contained in:
Yu-886 2025-03-14 14:44:37 +08:00
parent bd87790bf8
commit 187723b063
27 changed files with 5306 additions and 373 deletions

View File

@ -1,6 +1,6 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.16)
set(SERIAL_FLASHER_INTERFACE_UART true)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(usb_serial_jtag_echo)

View File

@ -0,0 +1,15 @@
set(SERIAL_FLASHER_INTERFACE_UART true)
file(GLOB PORT_SRCS "port/*.c" "src/*.c")
idf_component_register(
SRCS "flasher_common.c"
${PORT_SRCS}
INCLUDE_DIRS "."
"include"
"port"
"private_include"
REQUIRES driver
REQUIRES esp_timer
)

View File

@ -0,0 +1,510 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <sys/param.h>
#include <assert.h>
#include "esp_loader_io.h"
#include "esp_loader.h"
#include "example_common.h"
#ifndef SINGLE_TARGET_SUPPORT
// For esp8266, esp32, esp32s2
#define BOOTLOADER_ADDRESS_V0 0x1000
// For esp32s3 and later chips
#define BOOTLOADER_ADDRESS_V1 0x0
#define PARTITION_ADDRESS 0x8000
#define APPLICATION_ADDRESS 0x10000
extern const uint8_t ESP32_bootloader_bin[];
extern const uint32_t ESP32_bootloader_bin_size;
extern const uint8_t ESP32_bootloader_bin_md5[];
extern const uint8_t ESP32_hello_world_bin[];
extern const uint32_t ESP32_hello_world_bin_size;
extern const uint8_t ESP32_hello_world_bin_md5[];
extern const uint8_t ESP32_partition_table_bin[];
extern const uint32_t ESP32_partition_table_bin_size;
extern const uint8_t ESP32_partition_table_bin_md5[];
extern const uint8_t ESP32_S2_bootloader_bin[];
extern const uint32_t ESP32_S2_bootloader_bin_size;
extern const uint8_t ESP32_S2_bootloader_bin_md5[];
extern const uint8_t ESP32_S2_hello_world_bin[];
extern const uint32_t ESP32_S2_hello_world_bin_size;
extern const uint8_t ESP32_S2_hello_world_bin_md5[];
extern const uint8_t ESP32_S2_partition_table_bin[];
extern const uint32_t ESP32_S2_partition_table_bin_size;
extern const uint8_t ESP32_S2_partition_table_bin_md5[];
extern const uint8_t ESP32_S3_bootloader_bin[];
extern const uint32_t ESP32_S3_bootloader_bin_size;
extern const uint8_t ESP32_S3_bootloader_bin_md5[];
extern const uint8_t ESP32_S3_hello_world_bin[];
extern const uint32_t ESP32_S3_hello_world_bin_size;
extern const uint8_t ESP32_S3_hello_world_bin_md5[];
extern const uint8_t ESP32_S3_partition_table_bin[];
extern const uint32_t ESP32_S3_partition_table_bin_size;
extern const uint8_t ESP32_S3_partition_table_bin_md5[];
extern const uint8_t ESP8266_bootloader_bin[];
extern const uint32_t ESP8266_bootloader_bin_size;
extern const uint8_t ESP8266_bootloader_bin_md5[];
extern const uint8_t ESP8266_hello_world_bin[];
extern const uint32_t ESP8266_hello_world_bin_size;
extern const uint8_t ESP8266_hello_world_bin_md5[];
extern const uint8_t ESP8266_partition_table_bin[];
extern const uint32_t ESP8266_partition_table_bin_size;
extern const uint8_t ESP8266_partition_table_bin_md5[];
extern const uint8_t ESP32_H4_bootloader_bin[];
extern const uint32_t ESP32_H4_bootloader_bin_size;
extern const uint8_t ESP32_H4_bootloader_bin_md5[];
extern const uint8_t ESP32_H4_hello_world_bin[];
extern const uint32_t ESP32_H4_hello_world_bin_size;
extern const uint8_t ESP32_H4_hello_world_bin_md5[];
extern const uint8_t ESP32_H4_partition_table_bin[];
extern const uint32_t ESP32_H4_partition_table_bin_size;
extern const uint8_t ESP32_H4_partition_table_bin_md5[];
extern const uint8_t ESP32_H2_bootloader_bin[];
extern const uint32_t ESP32_H2_bootloader_bin_size;
extern const uint8_t ESP32_H2_bootloader_bin_md5[];
extern const uint8_t ESP32_H2_hello_world_bin[];
extern const uint32_t ESP32_H2_hello_world_bin_size;
extern const uint8_t ESP32_H2_hello_world_bin_md5[];
extern const uint8_t ESP32_H2_partition_table_bin[];
extern const uint32_t ESP32_H2_partition_table_bin_size;
extern const uint8_t ESP32_H2_partition_table_bin_md5[];
extern const uint8_t ESP32_C2_bootloader_bin[];
extern const uint32_t ESP32_C2_bootloader_bin_size;
extern const uint8_t ESP32_C2_bootloader_bin_md5[];
extern const uint8_t ESP32_C2_hello_world_bin[];
extern const uint32_t ESP32_C2_hello_world_bin_size;
extern const uint8_t ESP32_C2_hello_world_bin_md5[];
extern const uint8_t ESP32_C2_partition_table_bin[];
extern const uint32_t ESP32_C2_partition_table_bin_size;
extern const uint8_t ESP32_C2_partition_table_bin_md5[];
extern const uint8_t ESP32_C3_bootloader_bin[];
extern const uint32_t ESP32_C3_bootloader_bin_size;
extern const uint8_t ESP32_C3_bootloader_bin_md5[];
extern const uint8_t ESP32_C3_hello_world_bin[];
extern const uint32_t ESP32_C3_hello_world_bin_size;
extern const uint8_t ESP32_C3_hello_world_bin_md5[];
extern const uint8_t ESP32_C3_partition_table_bin[];
extern const uint32_t ESP32_C3_partition_table_bin_size;
extern const uint8_t ESP32_C3_partition_table_bin_md5[];
extern const uint8_t ESP32_C6_bootloader_bin[];
extern const uint32_t ESP32_C6_bootloader_bin_size;
extern const uint8_t ESP32_C6_bootloader_bin_md5[];
extern const uint8_t ESP32_C6_hello_world_bin[];
extern const uint32_t ESP32_C6_hello_world_bin_size;
extern const uint8_t ESP32_C6_hello_world_bin_md5[];
extern const uint8_t ESP32_C6_partition_table_bin[];
extern const uint32_t ESP32_C6_partition_table_bin_size;
extern const uint8_t ESP32_C6_partition_table_bin_md5[];
void get_example_binaries(target_chip_t target, example_binaries_t *bins)
{
if (target == ESP8266_CHIP) {
bins->boot.data = ESP8266_bootloader_bin;
bins->boot.size = ESP8266_bootloader_bin_size;
bins->boot.md5 = ESP8266_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V0;
bins->part.data = ESP8266_partition_table_bin;
bins->part.size = ESP8266_partition_table_bin_size;
bins->part.md5 = ESP8266_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP8266_hello_world_bin;
bins->app.size = ESP8266_hello_world_bin_size;
bins->app.md5 = ESP8266_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else if (target == ESP32_CHIP) {
bins->boot.data = ESP32_bootloader_bin;
bins->boot.size = ESP32_bootloader_bin_size;
bins->boot.md5 = ESP32_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V0;
bins->part.data = ESP32_partition_table_bin;
bins->part.size = ESP32_partition_table_bin_size;
bins->part.md5 = ESP32_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP32_hello_world_bin;
bins->app.size = ESP32_hello_world_bin_size;
bins->app.md5 = ESP32_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else if (target == ESP32S2_CHIP) {
bins->boot.data = ESP32_S2_bootloader_bin;
bins->boot.size = ESP32_S2_bootloader_bin_size;
bins->boot.md5 = ESP32_S2_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V0;
bins->part.data = ESP32_S2_partition_table_bin;
bins->part.size = ESP32_S2_partition_table_bin_size;
bins->part.md5 = ESP32_S2_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP32_S2_hello_world_bin;
bins->app.size = ESP32_S2_hello_world_bin_size;
bins->app.md5 = ESP32_S2_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else if (target == ESP32H2_CHIP) {
bins->boot.data = ESP32_H2_bootloader_bin;
bins->boot.size = ESP32_H2_bootloader_bin_size;
bins->boot.md5 = ESP32_H2_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V1;
bins->part.data = ESP32_H2_partition_table_bin;
bins->part.size = ESP32_H2_partition_table_bin_size;
bins->part.md5 = ESP32_H2_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP32_H2_hello_world_bin;
bins->app.size = ESP32_H2_hello_world_bin_size;
bins->app.md5 = ESP32_H2_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else if (target == ESP32C2_CHIP) {
bins->boot.data = ESP32_C2_bootloader_bin;
bins->boot.size = ESP32_C2_bootloader_bin_size;
bins->boot.md5 = ESP32_C2_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V1;
bins->part.data = ESP32_C2_partition_table_bin;
bins->part.size = ESP32_C2_partition_table_bin_size;
bins->part.md5 = ESP32_C2_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP32_C2_hello_world_bin;
bins->app.size = ESP32_C2_hello_world_bin_size;
bins->app.md5 = ESP32_C2_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else if (target == ESP32C3_CHIP) {
bins->boot.data = ESP32_C3_bootloader_bin;
bins->boot.size = ESP32_C3_bootloader_bin_size;
bins->boot.md5 = ESP32_C3_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V1;
bins->part.data = ESP32_C3_partition_table_bin;
bins->part.size = ESP32_C3_partition_table_bin_size;
bins->part.md5 = ESP32_C3_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP32_C3_hello_world_bin;
bins->app.size = ESP32_C3_hello_world_bin_size;
bins->app.md5 = ESP32_C3_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else if (target == ESP32C6_CHIP) {
bins->boot.data = ESP32_C6_bootloader_bin;
bins->boot.size = ESP32_C6_bootloader_bin_size;
bins->boot.md5 = ESP32_C6_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V1;
bins->part.data = ESP32_C6_partition_table_bin;
bins->part.size = ESP32_C6_partition_table_bin_size;
bins->part.md5 = ESP32_C6_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP32_C6_hello_world_bin;
bins->app.size = ESP32_C6_hello_world_bin_size;
bins->app.md5 = ESP32_C6_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else if (target == ESP32S3_CHIP) {
bins->boot.data = ESP32_S3_bootloader_bin;
bins->boot.size = ESP32_S3_bootloader_bin_size;
bins->boot.md5 = ESP32_S3_bootloader_bin_md5;
bins->boot.addr = BOOTLOADER_ADDRESS_V1;
bins->part.data = ESP32_S3_partition_table_bin;
bins->part.size = ESP32_S3_partition_table_bin_size;
bins->part.md5 = ESP32_S3_partition_table_bin_md5;
bins->part.addr = PARTITION_ADDRESS;
bins->app.data = ESP32_S3_hello_world_bin;
bins->app.size = ESP32_S3_hello_world_bin_size;
bins->app.md5 = ESP32_S3_hello_world_bin_md5;
bins->app.addr = APPLICATION_ADDRESS;
} else {
abort();
}
}
extern const uint8_t ESP32_app_bin[];
extern const uint32_t ESP32_app_bin_size;
extern const uint8_t ESP32_C2_app_bin[];
extern const uint32_t ESP32_C2_app_bin_size;
extern const uint8_t ESP32_C3_app_bin[];
extern const uint32_t ESP32_C3_app_bin_size;
extern const uint8_t ESP32_H2_app_bin[];
extern const uint32_t ESP32_H2_app_bin_size;
extern const uint8_t ESP32_H4_app_bin[];
extern const uint32_t ESP32_H4_app_bin_size;
extern const uint8_t ESP32_S3_app_bin[];
extern const uint32_t ESP32_S3_app_bin_size;
extern const uint8_t ESP32_C6_app_bin[];
extern const uint32_t ESP32_C6_app_bin_size;
void get_example_ram_app_binary(target_chip_t target, example_ram_app_binary_t *bin)
{
switch (target) {
case ESP32_CHIP: {
bin->ram_app.data = ESP32_app_bin;
bin->ram_app.size = ESP32_app_bin_size;
break;
}
case ESP32C2_CHIP: {
bin->ram_app.data = ESP32_C2_app_bin;
bin->ram_app.size = ESP32_C2_app_bin_size;
break;
}
case ESP32C3_CHIP: {
bin->ram_app.data = ESP32_C3_app_bin;
bin->ram_app.size = ESP32_C3_app_bin_size;
break;
}
case ESP32H2_CHIP: {
bin->ram_app.data = ESP32_H2_app_bin;
bin->ram_app.size = ESP32_H2_app_bin_size;
break;
}
case ESP32S3_CHIP: {
bin->ram_app.data = ESP32_S3_app_bin;
bin->ram_app.size = ESP32_S3_app_bin_size;
break;
}
case ESP32C6_CHIP: {
bin->ram_app.data = ESP32_C6_app_bin;
bin->ram_app.size = ESP32_C6_app_bin_size;
break;
}
default: {
abort();
}
}
}
#endif
static const char *get_error_string(const esp_loader_error_t error)
{
const char *mapping[ESP_LOADER_ERROR_INVALID_RESPONSE + 1] = {
"NONE", "UNKNOWN", "TIMEOUT", "IMAGE SIZE",
"INVALID MD5", "INVALID PARAMETER", "INVALID TARGET",
"UNSUPPORTED CHIP", "UNSUPPORTED FUNCTION", "INVALID RESPONSE"
};
assert(error <= ESP_LOADER_ERROR_INVALID_RESPONSE);
return mapping[error];
}
esp_loader_error_t connect_to_target(uint32_t higher_transmission_rate)
{
esp_loader_connect_args_t connect_config = ESP_LOADER_CONNECT_DEFAULT();
esp_loader_error_t err = esp_loader_connect(&connect_config);
if (err != ESP_LOADER_SUCCESS) {
printf("Cannot connect to target. Error: %s\n", get_error_string(err));
if (err == ESP_LOADER_ERROR_TIMEOUT) {
printf("Check if the host and the target are properly connected.\n");
} else if (err == ESP_LOADER_ERROR_INVALID_TARGET) {
printf("You could be using an unsupported chip, or chip revision.\n");
} else if (err == ESP_LOADER_ERROR_INVALID_RESPONSE) {
printf("Try lowering the transmission rate or using shorter wires to connect the host and the target.\n");
}
return err;
}
printf("Connected to target\n");
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
if (higher_transmission_rate && esp_loader_get_target() != ESP8266_CHIP) {
err = esp_loader_change_transmission_rate(higher_transmission_rate);
if (err == ESP_LOADER_ERROR_UNSUPPORTED_FUNC) {
printf("ESP8266 does not support change transmission rate command.");
return err;
} else if (err != ESP_LOADER_SUCCESS) {
printf("Unable to change transmission rate on target.");
return err;
} else {
err = loader_port_change_transmission_rate(higher_transmission_rate);
if (err != ESP_LOADER_SUCCESS) {
printf("Unable to change transmission rate.");
return err;
}
printf("Transmission rate changed.\n");
}
}
#endif /* SERIAL_FLASHER_INTERFACE_UART || SERIAL_FLASHER_INTERFACE_USB */
return ESP_LOADER_SUCCESS;
}
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
esp_loader_error_t connect_to_target_with_stub(const uint32_t current_transmission_rate,
const uint32_t higher_transmission_rate)
{
esp_loader_connect_args_t connect_config = ESP_LOADER_CONNECT_DEFAULT();
esp_loader_error_t err = esp_loader_connect_with_stub(&connect_config);
if (err != ESP_LOADER_SUCCESS) {
printf("Cannot connect to target. Error: %s\n", get_error_string(err));
if (err == ESP_LOADER_ERROR_TIMEOUT) {
printf("Check if the host and the target are properly connected.\n");
} else if (err == ESP_LOADER_ERROR_INVALID_TARGET) {
printf("You could be using an unsupported chip, or chip revision.\n");
} else if (err == ESP_LOADER_ERROR_INVALID_RESPONSE) {
printf("Try lowering the transmission rate or using shorter wires to connect the host and the target.\n");
}
return err;
}
printf("Connected to target\n");
if (higher_transmission_rate != current_transmission_rate) {
err = esp_loader_change_transmission_rate_stub(current_transmission_rate,
higher_transmission_rate);
if (err == ESP_LOADER_ERROR_UNSUPPORTED_FUNC) {
printf("ESP8266 does not support change transmission rate command.");
return err;
} else if (err != ESP_LOADER_SUCCESS) {
printf("Unable to change transmission rate on target.");
return err;
} else {
err = loader_port_change_transmission_rate(higher_transmission_rate);
if (err != ESP_LOADER_SUCCESS) {
printf("Unable to change transmission rate.");
return err;
}
printf("Transmission rate changed.\n");
}
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t flash_binary(const uint8_t *bin, size_t size, size_t address)
{
esp_loader_error_t err;
static uint8_t payload[1024];
const uint8_t *bin_addr = bin;
printf("Erasing flash (this may take a while)...\n");
err = esp_loader_flash_start(address, size, sizeof(payload));
if (err != ESP_LOADER_SUCCESS) {
printf("Erasing flash failed with error: %s.\n", get_error_string(err));
if (err == ESP_LOADER_ERROR_INVALID_PARAM) {
printf("If using Secure Download Mode, double check that the specified\
target flash size is correct.\n");
}
return err;
}
printf("Start programming\n");
size_t binary_size = size;
size_t written = 0;
while (size > 0) {
size_t to_read = MIN(size, sizeof(payload));
memcpy(payload, bin_addr, to_read);
err = esp_loader_flash_write(payload, to_read);
if (err != ESP_LOADER_SUCCESS) {
printf("\nPacket could not be written! Error %s.\n", get_error_string(err));
return err;
}
size -= to_read;
bin_addr += to_read;
written += to_read;
int progress = (int)(((float)written / binary_size) * 100);
printf("\rProgress: %d %%", progress);
};
printf("\nFinished programming\n");
#if MD5_ENABLED
err = esp_loader_flash_verify();
if (err == ESP_LOADER_ERROR_UNSUPPORTED_FUNC) {
printf("ESP8266 does not support flash verify command.");
return err;
} else if (err != ESP_LOADER_SUCCESS) {
printf("MD5 does not match. Error: %s\n", get_error_string(err));
return err;
}
printf("Flash verified\n");
#endif
return ESP_LOADER_SUCCESS;
}
#endif /* SERIAL_FLASHER_INTERFACE_UART || SERIAL_FLASHER_INTERFACE_USB */
esp_loader_error_t load_ram_binary(const uint8_t *bin)
{
printf("Start loading\n");
esp_loader_error_t err;
const esp_loader_bin_header_t *header = (const esp_loader_bin_header_t *)bin;
esp_loader_bin_segment_t segments[header->segments];
// Parse segments
uint32_t seg;
uint32_t *cur_seg_pos;
for (seg = 0, cur_seg_pos = (uint32_t *)(&bin[BIN_FIRST_SEGMENT_OFFSET]);
seg < header->segments;
seg++) {
segments[seg].addr = *cur_seg_pos++;
segments[seg].size = *cur_seg_pos++;
segments[seg].data = (uint8_t *)cur_seg_pos;
cur_seg_pos += (segments[seg].size) / 4;
}
// Download segments
for (seg = 0; seg < header->segments; seg++) {
printf("Downloading %"PRIu32" bytes at 0x%08"PRIx32"...\n", segments[seg].size, segments[seg].addr);
err = esp_loader_mem_start(segments[seg].addr, segments[seg].size, ESP_RAM_BLOCK);
if (err != ESP_LOADER_SUCCESS) {
printf("Loading to RAM could not be started. Error: %s.\n", get_error_string(err));
if (err == ESP_LOADER_ERROR_INVALID_PARAM) {
printf("Check if the chip has Secure Download Mode enabled.\n");
}
return err;
}
size_t remain_size = segments[seg].size;
uint8_t *data_pos = segments[seg].data;
while (remain_size > 0) {
size_t data_size = MIN(ESP_RAM_BLOCK, remain_size);
err = esp_loader_mem_write(data_pos, data_size);
if (err != ESP_LOADER_SUCCESS) {
printf("\nPacket could not be written! Error: %s.\n", get_error_string(err));
return err;
}
data_pos += data_size;
remain_size -= data_size;
}
}
err = esp_loader_mem_finish(header->entrypoint);
if (err != ESP_LOADER_SUCCESS) {
printf("\nLoading to RAM finished with error: %s.\n", get_error_string(err));
return err;
}
printf("\nFinished loading\n");
return ESP_LOADER_SUCCESS;
}

View File

@ -0,0 +1,66 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#define BIN_FIRST_SEGMENT_OFFSET 0x18
// Maximum block sized for RAM and Flash writes, respectively.
#define ESP_RAM_BLOCK 0x1800
typedef struct {
const uint8_t *data;
uint32_t size;
uint32_t addr;
const uint8_t *md5;
} partition_attr_t;
typedef struct {
partition_attr_t boot;
partition_attr_t part;
partition_attr_t app;
} example_binaries_t;
typedef struct {
partition_attr_t ram_app;
} example_ram_app_binary_t;
/**
* @brief esptool portable bin header format
*/
typedef struct example_bin_header {
uint8_t magic;
uint8_t segments;
uint8_t flash_mode;
uint8_t flash_size_freq;
uint32_t entrypoint;
} example_bin_header_t;
/**
* @brief esptool portable bin segment format
*/
typedef struct example_bin_segment {
uint32_t addr;
uint32_t size;
uint8_t *data;
} example_bin_segment_t;
void get_example_binaries(target_chip_t target, example_binaries_t *binaries);
void get_example_ram_app_binary(target_chip_t target, example_ram_app_binary_t *bin);
esp_loader_error_t connect_to_target(uint32_t higher_transmission_rate);
esp_loader_error_t connect_to_target_with_stub(uint32_t current_transmission_rate,
uint32_t higher_transmission_rate);
esp_loader_error_t flash_binary(const uint8_t *bin, size_t size, size_t address);
esp_loader_error_t load_ram_binary(const uint8_t *bin);

View File

@ -0,0 +1,452 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Used for backwards compatibility with the previous API */
#define esp_loader_change_baudrate esp_loader_change_transmission_rate
#define SERIAL_FLASHER_INTERFACE_UART
/**
* Macro which can be used to check the error code,
* and return in case the code is not ESP_LOADER_SUCCESS.
*/
#define RETURN_ON_ERROR(x) do { \
esp_loader_error_t _err_ = (x); \
if (_err_ != ESP_LOADER_SUCCESS) { \
return _err_; \
} \
} while(0)
/**
* @brief Error codes
*/
typedef enum {
ESP_LOADER_SUCCESS, /*!< Success */
ESP_LOADER_ERROR_FAIL, /*!< Unspecified error */
ESP_LOADER_ERROR_TIMEOUT, /*!< Timeout elapsed */
ESP_LOADER_ERROR_IMAGE_SIZE, /*!< Image size to flash is larger than flash size */
ESP_LOADER_ERROR_INVALID_MD5, /*!< Computed and received MD5 does not match */
ESP_LOADER_ERROR_INVALID_PARAM, /*!< Invalid parameter passed to function */
ESP_LOADER_ERROR_INVALID_TARGET, /*!< Connected target is invalid */
ESP_LOADER_ERROR_UNSUPPORTED_CHIP, /*!< Attached chip is not supported */
ESP_LOADER_ERROR_UNSUPPORTED_FUNC, /*!< Function is not supported on attached target */
ESP_LOADER_ERROR_INVALID_RESPONSE /*!< Internal error */
} esp_loader_error_t;
/**
* @brief Supported targets
*/
typedef enum {
ESP8266_CHIP = 0,
ESP32_CHIP = 1,
ESP32S2_CHIP = 2,
ESP32C3_CHIP = 3,
ESP32S3_CHIP = 4,
ESP32C2_CHIP = 5,
ESP32_RESERVED0_CHIP = 6, // Reserved for future use
ESP32H2_CHIP = 7,
ESP32C6_CHIP = 8,
ESP_MAX_CHIP = 9,
ESP_UNKNOWN_CHIP = 9
} target_chip_t;
/**
* @brief Application binary header
*/
typedef struct {
uint8_t magic;
uint8_t segments;
uint8_t flash_mode;
uint8_t flash_size_freq;
uint32_t entrypoint;
} esp_loader_bin_header_t;
/**
* @brief Segment binary header
*/
typedef struct {
uint32_t addr;
uint32_t size;
uint8_t *data;
} esp_loader_bin_segment_t;
typedef struct {
target_chip_t target_chip;
uint32_t eco_version; // Not present on ESP32-S2
bool secure_boot_enabled;
bool secure_boot_aggressive_revoke_enabled;
bool secure_download_mode_enabled;
bool secure_boot_revoked_keys[3];
bool jtag_software_disabled;
bool jtag_hardware_disabled;
bool usb_disabled;
bool flash_encryption_enabled;
bool dcache_in_uart_download_disabled;
bool icache_in_uart_download_disabled;
} esp_loader_target_security_info_t;
/**
* @brief Connection arguments
*/
typedef struct {
uint32_t sync_timeout; /*!< Maximum time to wait for response from serial interface. */
int32_t trials; /*!< Number of trials to connect to target. If greater than 1,
100 millisecond delay is inserted after each try. */
} esp_loader_connect_args_t;
#define ESP_LOADER_CONNECT_DEFAULT() { \
.sync_timeout = 100, \
.trials = 10, \
}
/**
* @brief Connects to the target
*
* @param connect_args[in] Timing parameters to be used for connecting to target.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args);
/**
* @brief Returns attached target chip.
*
* @warning This function can only be called after connection with target
* has been successfully established by calling esp_loader_connect().
*
* @return One of target_chip_t
*/
target_chip_t esp_loader_get_target(void);
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
/**
* @brief Connects to the target while using the flasher stub
*
* @param connect_args[in] Timing parameters to be used for connecting to target.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_connect_with_stub(esp_loader_connect_args_t *connect_args);
#ifdef SERIAL_FLASHER_INTERFACE_UART
/**
* @brief Connects to the target running in secure download mode
*
* Secure download mode is a special mode in which the commands accepted by the boot ROM
* are limited to a safe subset. It is enabled by burning an efuse on the target.
* Read more about it here:
* https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/kconfig.html#config-secure-uart-rom-dl-mode
*
* @param connect_args[in] Timing parameters to be used for connecting to target.
* @param flash_size Flash size of the target chip.
* @param target_chip Target chip. Used for the ESP32 and ESP8266, which do not support the
* GET_SECURITY_INFO command required to identify the target in secure
* download mode. Leave as ESP_UNKNOWN_CHIP for autodetection of newer chips.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_connect_secure_download_mode(esp_loader_connect_args_t *connect_args,
uint32_t flash_size, target_chip_t target_chip);
#endif /* SERIAL_FLASHER_INTERFACE_UART */
/**
* @brief Initiates flash operation
*
* @param offset[in] Address from which flash operation will be performed. Must be 4 byte aligned.
* @param image_size[in] Size of the whole binary to be loaded into flash. Must be 4 byte aligned.
* @param block_size[in] Size of buffer used in subsequent calls to esp_loader_flash_write.
*
* @note image_size is size of the whole image, whereas, block_size is chunk of data sent
* to the target, each time esp_loader_flash_write function is called.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size);
/**
* @brief Writes supplied data to target's flash memory.
*
* @param payload[in] Data to be flashed into target's memory.
* @param size[in] Size of payload in bytes.
*
* @note size must not be greater that block_size supplied to previously called
* esp_loader_flash_start function. If size is less than block_size,
* remaining bytes of payload buffer will be padded with 0xff.
* Therefore, size of payload buffer has to be equal or greater than block_size.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size);
/**
* @brief Ends flash operation.
*
* @param reboot[in] reboot the target if true.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_finish(bool reboot);
/**
* @brief Detects the size of the flash chip used by target
*
* @param flash_size[out] Flash size detected in bytes
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_UNSUPPORTED_CHIP The target flash chip is not known
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target chip is running in secure download mode
*/
esp_loader_error_t esp_loader_flash_detect_size(uint32_t *flash_size);
/**
* @brief Reads from the target flash.
*
* @param buf[out] Buffer to read into
* @param address[in] Flash address to read from.
* @param length[in] Read length in bytes.
*
* @note Higher read speeds can be achieved by using the flasher stub.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_UNSUPPORTED_CHIP The target flash chip is not known
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target chip is running in secure download mode
*/
esp_loader_error_t esp_loader_flash_read(uint8_t *buf, uint32_t address, uint32_t length);
/**
* @brief Change baud rate of the stub running on the target
*
* @note Baud rate has to be also adjusted accordingly on host MCU, as
* target's baud rate is changed upon return from this function.
*
* @param old_transmission_rate[in] The baudrate to be changed
* @param new_transmission_rate[in] The new baud rate to be set.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The stub is not running
*/
esp_loader_error_t esp_loader_change_transmission_rate_stub(uint32_t old_transmission_rate,
uint32_t new_transmission_rate);
/**
* @brief Get the security info of the target chip
*
* @note The ESP32 and ESP8266 do not support this command.
*
* @param security_info[out] The security info structure
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Either a timeout event or the target chip responded with
* a different command code, due to not supporting the command.
* - ESP_LOADER_ERROR_INVALID_RESPONSE The target reply is malformed.
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target chip does not support this command.
*/
esp_loader_error_t esp_loader_get_security_info(esp_loader_target_security_info_t *security_info);
#endif /* SERIAL_FLASHER_INTERFACE_UART || SERIAL_FLASHER_INTERFACE_USB */
/**
* @brief Initiates mem operation, initiates loading for program into target RAM
*
* @param offset[in] Address from which mem operation will be performed.
* @param size[in] Size of the whole binary to be loaded into mem.
* @param block_size[in] Size of buffer used in subsequent calls to esp_loader_mem_write.
*
* @note image_size is size of the whole image, whereas, block_size is chunk of data sent
* to the target, each time esp_mem_flash_write function is called.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target is running in secure download mode
*/
esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size);
/**
* @brief Writes supplied data to target's mem memory.
*
* @param payload[in] Data to be loaded into target's memory.
* @param size[in] Size of data in bytes.
*
* @note size must not be greater that block_size supplied to previously called
* esp_loader_mem_start function.
* Therefore, size of data buffer has to be equal or greater than block_size.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target is running in secure download mode
*/
esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size);
/**
* @brief Ends mem operation, finish loading for program into target RAM
* and send the entrypoint of ram_loadable app
*
* @param entrypoint[in] entrypoint of ram program.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target is running in secure download mode
*/
esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint);
#ifndef SERIAL_FLASHER_INTERFACE_SDIO
/**
* @brief Reads te MAC of the connected chip.
*
* @param mac[out] 6 byte MAC address of the chip
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target is running in secure download mode
*/
esp_loader_error_t esp_loader_read_mac(uint8_t *mac);
/**
* @brief Writes register.
*
* @param address[in] Address of register.
* @param reg_value[in] New register value.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target is running in secure download mode
*/
esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value);
/**
* @brief Reads register.
*
* @param address[in] Address of register.
* @param reg_value[out] Register value.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC The target is running in secure download mode
*/
esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value);
/**
* @brief Change baud rate.
*
* @note Baud rate has to be also adjusted accordingly on host MCU, as
* target's baud rate is changed upon return from this function.
*
* @param transmission_rate[in] new baud rate to be set.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Either the target is running in secure download
* mode or the stub is running on the target.
*/
esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate);
#endif /* SERIAL_FLASHER_INTERFACE_SDIO */
#if MD5_ENABLED
/**
* @brief Verify target's flash integrity by checking with a known MD5 checksum
* for a specified offset and length.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_INVALID_MD5 MD5 does not match
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target
* - ESP_LOADER_ERROR_IMAGE_SIZE Flash region specified is beyond the flash end
*/
esp_loader_error_t esp_loader_flash_verify_known_md5(uint32_t address,
uint32_t size,
const uint8_t *expected_md5);
/**
* @brief Verify target's flash integrity by checking MD5.
* MD5 checksum is computed from data pushed to target's memory by calling
* esp_loader_flash_write() function and compared against target's MD5.
* Target computes checksum based on offset and image_size passed to
* esp_loader_flash_start() function.
*
* @note This function is only available if MD5_ENABLED is set.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_INVALID_MD5 MD5 does not match
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target
* - ESP_LOADER_ERROR_IMAGE_SIZE Flash region specified is beyond the flash end
*/
esp_loader_error_t esp_loader_flash_verify(void);
#endif /* MD5_ENABLED */
/**
* @brief Toggles reset pin.
*/
void esp_loader_reset_target(void);
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,132 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include "esp_loader.h"
#ifdef __cplusplus
extern "C" {
#endif
#define SERIAL_FLASHER_RESET_INVERT 0
#define SERIAL_FLASHER_BOOT_INVERT 0
#define SERIAL_FLASHER_INTERFACE_SPI
#ifndef SERIAL_FLASHER_INTERFACE_SDIO
/**
* @brief Changes the transmission rate of the used peripheral.
*/
esp_loader_error_t loader_port_change_transmission_rate(uint32_t transmission_rate);
#endif
/**
* @brief Writes data over the io interface.
*
* @param data[in] Buffer with data to be written.
* @param size[in] Size of data in bytes.
* @param timeout[in] Timeout in milliseconds.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed
*/
#ifndef SERIAL_FLASHER_INTERFACE_SDIO
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout);
#else
esp_loader_error_t loader_port_write(uint32_t function, uint32_t addr, const uint8_t *data,
uint16_t size, uint32_t timeout);
#endif
/**
* @brief Reads data from the io interface.
*
* @param data[out] Buffer into which received data will be written.
* @param size[in] Number of bytes to read.
* @param timeout[in] Timeout in milliseconds.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed
*/
#ifndef SERIAL_FLASHER_INTERFACE_SDIO
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout);
#else
esp_loader_error_t loader_port_read(uint32_t function, uint32_t addr, uint8_t *data,
uint16_t size, uint32_t timeout);
#endif
/**
* @brief Delay in milliseconds.
*
* @param ms[in] Number of milliseconds.
*
*/
void loader_port_delay_ms(uint32_t ms);
/**
* @brief Starts timeout timer.
*
* @param ms[in] Number of milliseconds.
*
*/
void loader_port_start_timer(uint32_t ms);
/**
* @brief Returns remaining time since timer was started by calling esp_loader_start_timer.
* 0 if timer has elapsed.
*
* @return Number of milliseconds.
*
*/
uint32_t loader_port_remaining_time(void);
/**
* @brief Asserts bootstrap pins to enter boot mode and toggles reset pin.
*
* @note Reset pin should stay asserted for at least 20 milliseconds.
*/
void loader_port_enter_bootloader(void);
/**
* @brief Toggles reset pin.
*
* @note Reset pin should stay asserted for at least 20 milliseconds.
*/
void loader_port_reset_target(void);
/**
* @brief Function can be defined by user to print debug message.
*
* @note Empty weak function is used, otherwise.
*
*/
void loader_port_debug_print(const char *str);
#ifdef SERIAL_FLASHER_INTERFACE_SPI
/**
* @brief Sets the chip select to a defined level
*/
void loader_port_spi_set_cs(uint32_t level);
#endif /* SERIAL_FLASHER_INTERFACE_SPI */
#ifdef SERIAL_FLASHER_INTERFACE_SDIO
esp_loader_error_t loader_port_sdio_card_init(void);
#endif /* SERIAL_FLASHER_INTERFACE_SDIO */
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,24 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#warning Please replace serial_io.h with esp_loader_io.h and change the function names \
to match the new API
/* Defines used to avoid breaking existing ports */
#define loader_port_change_baudrate loader_port_change_transmission_rate
#define loader_port_serial_write loader_port_write
#define loader_port_serial_read loader_port_read
#include "esp_loader_io.h"

View File

@ -0,0 +1,192 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "esp32_port.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_timer.h"
#include "esp_log.h"
#include "esp_idf_version.h"
#include <unistd.h>
#if SERIAL_FLASHER_DEBUG_TRACE
static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write)
{
static bool write_prev = false;
if (write_prev != write) {
write_prev = write;
printf("\n--- %s ---\n", write ? "WRITE" : "READ");
}
for (uint32_t i = 0; i < size; i++) {
printf("%02x ", data[i]);
}
}
#endif
static int64_t s_time_end;
static int32_t s_uart_port;
static int32_t s_reset_trigger_pin;
static int32_t s_gpio0_trigger_pin;
static bool s_peripheral_needs_deinit;
esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config)
{
s_uart_port = config->uart_port;
s_reset_trigger_pin = config->reset_trigger_pin;
s_gpio0_trigger_pin = config->gpio0_trigger_pin;
// Initialize UART
if (!config->dont_initialize_peripheral) {
uart_config_t uart_config = {
.baud_rate = config->baud_rate,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
.source_clk = UART_SCLK_DEFAULT,
#endif
};
int rx_buffer_size = config->rx_buffer_size ? config->rx_buffer_size : 400;
int tx_buffer_size = config->tx_buffer_size ? config->tx_buffer_size : 400;
QueueHandle_t *uart_queue = config->uart_queue ? config->uart_queue : NULL;
int queue_size = config->queue_size ? config->queue_size : 0;
// Sets pin current strength to 40 mA, because some pins default to 10 mA,
// which is not enough when USB-UART is also present on the UART lines (at least 20 mA should be sufficient).
if ( gpio_set_drive_capability(config->uart_tx_pin, GPIO_DRIVE_CAP_3) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
if ( uart_param_config(s_uart_port, &uart_config) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
if ( uart_set_pin(s_uart_port, config->uart_tx_pin, config->uart_rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
if ( uart_driver_install(s_uart_port, rx_buffer_size, tx_buffer_size, queue_size, uart_queue, 0) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
s_peripheral_needs_deinit = true;
}
// Initialize boot pin selection pins
gpio_reset_pin(s_reset_trigger_pin);
gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT);
gpio_reset_pin(s_gpio0_trigger_pin);
gpio_set_pull_mode(s_gpio0_trigger_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_gpio0_trigger_pin, GPIO_MODE_OUTPUT);
return ESP_LOADER_SUCCESS;
}
void loader_port_esp32_deinit(void)
{
if (s_peripheral_needs_deinit) {
uart_driver_delete(s_uart_port);
}
}
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout)
{
uart_write_bytes(s_uart_port, (const char *)data, size);
esp_err_t err = uart_wait_tx_done(s_uart_port, pdMS_TO_TICKS(timeout));
if (err == ESP_OK) {
#if SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, size, true);
#endif
return ESP_LOADER_SUCCESS;
} else if (err == ESP_ERR_TIMEOUT) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout)
{
int read = uart_read_bytes(s_uart_port, data, size, pdMS_TO_TICKS(timeout));
if (read < 0) {
return ESP_LOADER_ERROR_FAIL;
} else if (read < size) {
#if SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, read, false);
#endif
return ESP_LOADER_ERROR_TIMEOUT;
} else {
#if SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, read, false);
#endif
return ESP_LOADER_SUCCESS;
}
}
void loader_port_enter_bootloader(void)
{
gpio_set_level(s_gpio0_trigger_pin, SERIAL_FLASHER_BOOT_INVERT ? 1 : 0);
loader_port_reset_target();
loader_port_delay_ms(CONFIG_SERIAL_FLASHER_BOOT_HOLD_TIME_MS);
gpio_set_level(s_gpio0_trigger_pin, SERIAL_FLASHER_BOOT_INVERT ? 0 : 1);
}
void loader_port_reset_target(void)
{
gpio_set_level(s_reset_trigger_pin, SERIAL_FLASHER_RESET_INVERT ? 1 : 0);
loader_port_delay_ms(CONFIG_SERIAL_FLASHER_RESET_HOLD_TIME_MS);
gpio_set_level(s_reset_trigger_pin, SERIAL_FLASHER_RESET_INVERT ? 0 : 1);
}
void loader_port_delay_ms(uint32_t ms)
{
usleep(ms * 1000);
}
void loader_port_start_timer(uint32_t ms)
{
s_time_end = esp_timer_get_time() + ms * 1000;
}
uint32_t loader_port_remaining_time(void)
{
int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000;
return (remaining > 0) ? (uint32_t)remaining : 0;
}
void loader_port_debug_print(const char *str)
{
printf("DEBUG: %s\n", str);
}
esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate)
{
esp_err_t err = uart_set_baudrate(s_uart_port, baudrate);
return (err == ESP_OK) ? ESP_LOADER_SUCCESS : ESP_LOADER_ERROR_FAIL;
}

View File

@ -0,0 +1,61 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "esp_loader_io.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
uint32_t baud_rate; /*!< Initial baud rate, can be changed later */
uint32_t uart_port; /*!< UART port */
uint32_t uart_rx_pin; /*!< This pin will be configured as UART Rx pin */
uint32_t uart_tx_pin; /*!< This pin will be configured as UART Tx pin */
uint32_t reset_trigger_pin; /*!< This pin will be used to reset target chip */
uint32_t gpio0_trigger_pin; /*!< This pin will be used to toggle set IO0 of target chip */
uint32_t rx_buffer_size; /*!< Set to zero for default RX buffer size */
uint32_t tx_buffer_size; /*!< Set to zero for default TX buffer size */
uint32_t queue_size; /*!< Set to zero for default UART queue size */
QueueHandle_t *uart_queue; /*!< Set to NULL, if UART queue handle is not
necessary. Otherwise, it will be assigned here */
bool dont_initialize_peripheral; /* Use if the peripheral has already been initialized,
useful when using the peripheral for multiple
purposes (e.g. monitoring) */
} loader_esp32_config_t;
/**
* @brief Initializes serial interface.
*
* @param baud_rate[in] Communication speed.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_FAIL Initialization failure
*/
esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config);
/**
* @brief Deinitialize serial interface.
*/
void loader_port_esp32_deinit(void);
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,44 @@
/* Copyright 2020-2025 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// auto-generated stubs from esp-flasher-stub v0.3.0
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include "esp_loader.h"
#ifdef __cplusplus
extern "C" {
#endif
bool esp_stub_get_running(void);
void esp_stub_set_running(bool stub_status);
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
typedef struct {
esp_loader_bin_header_t header;
esp_loader_bin_segment_t segments[2];
} esp_stub_t;
extern const esp_stub_t esp_stub[ESP_MAX_CHIP];
#endif
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,38 @@
/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include "esp_loader.h"
typedef struct {
uint32_t cmd;
uint32_t usr;
uint32_t usr1;
uint32_t usr2;
uint32_t w0;
uint32_t mosi_dlen;
uint32_t miso_dlen;
} target_registers_t;
esp_loader_error_t loader_detect_chip(target_chip_t *target, const target_registers_t **regs);
#ifndef SERIAL_FLASHER_INTERFACE_SDIO
esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config);
bool encryption_in_begin_flash_cmd(target_chip_t target);
esp_loader_error_t loader_read_mac(target_chip_t target_code, uint8_t *mac);
target_chip_t target_from_chip_id(uint32_t chip_id);
#endif

View File

@ -0,0 +1,28 @@
/*
* MD5 hash implementation and interface functions
* Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct MD5Context {
uint32_t buf[4];
uint32_t bits[2];
uint8_t in[64];
};
void MD5Init(struct MD5Context *context);
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len);
void MD5Final(unsigned char digest[16], struct MD5Context *context);
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,293 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include "esp_loader.h"
#ifdef __cplusplus
extern "C" {
#endif
#define STATUS_FAILURE 1
#define STATUS_SUCCESS 0
#define READ_DIRECTION 1
#define WRITE_DIRECTION 0
#define MD5_SIZE_ROM 32
#define MD5_SIZE_STUB 16
// Maximum block sized for RAM and Flash writes, respectively.
#define ESP_RAM_BLOCK 0x1800
#ifndef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef ROUNDUP
#define ROUNDUP(a, b) ((((unsigned)a + (unsigned)b - 1) / (unsigned)b) * (unsigned)b)
#endif
#define MAX_RESP_DATA_SIZE 64
#define READ_FLASH_ROM_DATA_SIZE 64
typedef enum __attribute__((packed))
{
FLASH_BEGIN = 0x02,
FLASH_DATA = 0x03,
FLASH_END = 0x04,
MEM_BEGIN = 0x05,
MEM_END = 0x06,
MEM_DATA = 0x07,
SYNC = 0x08,
WRITE_REG = 0x09,
READ_REG = 0x0a,
SPI_SET_PARAMS = 0x0b,
SPI_ATTACH = 0x0d,
READ_FLASH_ROM = 0x0e,
CHANGE_BAUDRATE = 0x0f,
FLASH_DEFL_BEGIN = 0x10,
FLASH_DEFL_DATA = 0x11,
FLASH_DEFL_END = 0x12,
SPI_FLASH_MD5 = 0x13,
GET_SECURITY_INFO = 0x14,
READ_FLASH_STUB = 0xd2,
} command_t;
typedef enum __attribute__((packed))
{
RESPONSE_OK = 0x00,
INVALID_COMMAND = 0x05, // parameters or length field is invalid
COMMAND_FAILED = 0x06, // Failed to act on received message
INVALID_CRC = 0x07, // Invalid CRC in message
FLASH_WRITE_ERR = 0x08, // After writing a block of data to flash, the ROM loader reads the value back and the 8-bit CRC is compared to the data read from flash. If they don't match, this error is returned.
FLASH_READ_ERR = 0x09, // SPI read failed
READ_LENGTH_ERR = 0x0a, // SPI read request length is too long
DEFLATE_ERROR = 0x0b, // ESP32 compressed uploads only
} error_code_t;
typedef struct __attribute__((packed))
{
uint8_t direction;
uint8_t command; // One of command_t
uint16_t size;
uint32_t checksum;
} command_common_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t erase_size;
uint32_t packet_count;
uint32_t packet_size;
uint32_t offset;
uint32_t encrypted;
} flash_begin_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t data_size;
uint32_t sequence_number;
uint32_t zero_0;
uint32_t zero_1;
} data_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t stay_in_loader;
} flash_end_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t size;
} flash_read_rom_cmd;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t total_size;
uint32_t packet_data_size;
uint32_t max_inflight_packets;
} flash_read_stub_cmd;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t total_size;
uint32_t blocks;
uint32_t block_size;
uint32_t offset;
} mem_begin_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t stay_in_loader;
uint32_t entry_point_address;
} mem_end_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint8_t sync_sequence[36];
} sync_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t value;
uint32_t mask;
uint32_t delay_us;
} write_reg_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
} read_reg_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t configuration;
uint32_t zero; // ESP32 ROM only
} spi_attach_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t new_baudrate;
uint32_t old_baudrate;
} change_baudrate_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t size;
uint32_t reserved_0;
uint32_t reserved_1;
} spi_flash_md5_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
} get_security_info_command_t;
typedef struct __attribute__((packed))
{
uint8_t direction;
uint8_t command; // One of command_t
uint16_t size;
uint32_t value;
} common_response_t;
typedef struct __attribute__((packed))
{
uint8_t failed;
uint8_t error;
} response_status_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t id;
uint32_t total_size;
uint32_t block_size;
uint32_t sector_size;
uint32_t page_size;
uint32_t status_mask;
} write_spi_command_t;
#define GET_SECURITY_INFO_SECURE_BOOT_EN (1 << 0)
#define GET_SECURITY_INFO_SECURE_BOOT_AGGRESSIVE_REVOKE (1 << 1)
#define GET_SECURITY_INFO_SECURE_DOWNLOAD_ENABLE (1 << 2)
#define GET_SECURITY_INFO_SECURE_BOOT_KEY_REVOKE0 (1 << 3)
#define GET_SECURITY_INFO_SECURE_BOOT_KEY_REVOKE1 (1 << 4)
#define GET_SECURITY_INFO_SECURE_BOOT_KEY_REVOKE2 (1 << 5)
#define GET_SECURITY_INFO_SOFT_DIS_JTAG (1 << 6)
#define GET_SECURITY_INFO_HARD_DIS_JTAG (1 << 7)
#define GET_SECURITY_INFO_DIS_USB (1 << 8)
#define GET_SECURITY_INFO_DIS_DOWNLOAD_DCACHE (1 << 9)
#define GET_SECURITY_INFO_DIS_DOWNLOAD_ICACHE (1 << 10)
typedef struct __attribute__((packed))
{
uint32_t flags;
uint8_t flash_crypt_cnt;
uint8_t key_purposes[7];
uint32_t chip_id;
uint32_t eco_version;
} get_security_info_response_data_t;
esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args);
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
esp_loader_error_t loader_flash_begin_cmd(uint32_t offset, uint32_t erase_size, uint32_t block_size, uint32_t blocks_to_write, bool encryption);
esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size);
esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader);
esp_loader_error_t loader_flash_read_rom_cmd(uint32_t address, uint8_t *data);
esp_loader_error_t loader_flash_read_stub_cmd(uint32_t address, uint32_t size, uint32_t size_per_packet);
esp_loader_error_t loader_sync_cmd(void);
esp_loader_error_t loader_spi_attach_cmd(uint32_t config);
esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out);
esp_loader_error_t loader_spi_parameters(uint32_t total_size);
esp_loader_error_t loader_run_stub(target_chip_t target);
esp_loader_error_t loader_get_security_info_cmd(get_security_info_response_data_t *response,
uint32_t *response_recv_size);
#endif /* SERIAL_FLASHER_INTERFACE_UART || SERIAL_FLASHER_INTERFACE_USB */
esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size);
esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size);
esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint);
#ifndef SERIAL_FLASHER_INTERFACE_SDIO
esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value, uint32_t mask, uint32_t delay_us);
esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg);
esp_loader_error_t loader_change_baudrate_cmd(uint32_t new_baudrate, uint32_t old_baudrate);
#endif /* SERIAL_FLASHER_INTERFACE_SDIO */
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,40 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "esp_loader.h"
#include "protocol.h"
typedef struct {
const void *cmd;
size_t cmd_size;
const void *data; // Set to NULL if the command has no data
size_t data_size;
void *resp_data; // Set to NULL if the response has no data
size_t resp_data_size;
uint32_t *resp_data_recv_size; /* Out parameter indicating actual size of the response read
for commands where response size can vary, in which
case resp_data_size is the maximum response data size allowed.
Set to NULL to require fixed response size of resp_data_size. */
uint32_t *reg_value; // Out parameter for the READ_REG command, will return zero otherwise
} send_cmd_config;
void log_loader_internal_error(error_code_t error);
esp_loader_error_t send_cmd(const send_cmd_config *config);

View File

@ -0,0 +1,73 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define SIP_HDR_F_SYNC 0x4
#define SIP_IFIDX_MASK 0xf0
#define SIP_IFIDX_S 4
#define SIP_TYPE_MASK 0x0f
#define SIP_TYPE_S 0
#define SIP_PACKET_SIZE 256
typedef enum {
SIP_PACKET_TYPE_CTRL = 0,
SIP_PACKET_TYPE_DATA,
} sip_packet_type_t;
typedef enum {
SIP_CMD_ID_GET_VER = 0,
SIP_CMD_ID_WRITE_MEMORY = 1,
SIP_CMD_ID_BOOTUP = 5,
} sip_cmd_id_t;
typedef struct __attribute__((packed))
{
uint8_t tid;
uint8_t ac;
uint8_t p2p: 1,
enc_flag: 7;
uint8_t hw_kid;
} sip_tx_data_info_t;
typedef struct __attribute__((packed))
{
union {
uint32_t cmdid;
sip_tx_data_info_t dinfo;
} u;
} sip_tx_info_t;
typedef struct __attribute__((packed))
{
uint8_t fc[2];
uint16_t len; // Length of packet, including the header itself, must align to 4
union {
uint32_t recycled_credits;
sip_tx_info_t tx_info;
} u;
uint32_t sequence_num;
} sip_header_t;
typedef struct __attribute__((packed))
{
uint32_t addr;
uint32_t len;
} sip_cmd_write_memory;
typedef struct __attribute__((packed))
{
uint32_t boot_addr;
uint32_t discard_link;
} sip_cmd_bootup;

View File

@ -0,0 +1,26 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "esp_loader.h"
#include <stdint.h>
#include <stdlib.h>
esp_loader_error_t SLIP_receive_packet(uint8_t *buff, size_t max_size, size_t *recv_size);
esp_loader_error_t SLIP_send(const uint8_t *data, size_t size);
esp_loader_error_t SLIP_send_delimiter(void);

View File

@ -0,0 +1,769 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "protocol.h"
#include "esp_loader_io.h"
#include "esp_loader.h"
#include "esp_stubs.h"
#include "esp_targets.h"
#include "md5_hash.h"
#include "slip.h"
#include <string.h>
#include <assert.h>
#define SHORT_TIMEOUT 100
#define DEFAULT_TIMEOUT 1000
#define DEFAULT_FLASH_TIMEOUT 3000
#define LOAD_RAM_TIMEOUT_PER_MB 2000000
#define MD5_TIMEOUT_PER_MB 8000
#define SERIAL_FLASHER_WRITE_BLOCK_RETRIES 3
typedef enum {
SPI_FLASH_READ_ID = 0x9F
} spi_flash_cmd_t;
static const target_registers_t *s_reg = NULL;
static target_chip_t s_target = ESP_UNKNOWN_CHIP;
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
#define DEFAULT_FLASH_SIZE 2 * 1024 * 1024
static uint32_t s_flash_write_size = 0;
static uint32_t s_target_flash_size = 0;
#endif
#if MD5_ENABLED
static struct MD5Context s_md5_context;
static uint32_t s_start_address;
static uint32_t s_image_size;
static inline void init_md5(uint32_t address, uint32_t size)
{
s_start_address = address;
s_image_size = size;
MD5Init(&s_md5_context);
}
static inline void md5_update(const uint8_t *data, uint32_t size)
{
MD5Update(&s_md5_context, data, size);
}
static inline void md5_final(uint8_t digets[16])
{
MD5Final(digets, &s_md5_context);
}
#endif
static uint32_t timeout_per_mb(uint32_t size_bytes, uint32_t time_per_mb)
{
uint32_t timeout = time_per_mb * (size_bytes / 1e6);
return MAX(timeout, DEFAULT_FLASH_TIMEOUT);
}
esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args)
{
loader_port_enter_bootloader();
RETURN_ON_ERROR(loader_initialize_conn(connect_args));
RETURN_ON_ERROR(loader_detect_chip(&s_target, &s_reg));
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
s_target_flash_size = 0;
if (s_target == ESP8266_CHIP) {
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_flash_begin_cmd(0, 0, 0, 0, s_target);
} else {
uint32_t spi_config;
RETURN_ON_ERROR( loader_read_spi_config(s_target, &spi_config) );
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_spi_attach_cmd(spi_config);
}
#endif /* SERIAL_FLASHER_INTERFACE_UART || SERIAL_FLASHER_INTERFACE_USB */
return ESP_LOADER_SUCCESS;
}
target_chip_t esp_loader_get_target(void)
{
return s_target;
}
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
esp_loader_error_t esp_loader_connect_with_stub(esp_loader_connect_args_t *connect_args)
{
s_target_flash_size = 0;
loader_port_enter_bootloader();
RETURN_ON_ERROR(loader_initialize_conn(connect_args));
RETURN_ON_ERROR(loader_detect_chip(&s_target, &s_reg));
RETURN_ON_ERROR(loader_run_stub(s_target));
return ESP_LOADER_SUCCESS;
}
#ifdef SERIAL_FLASHER_INTERFACE_UART
esp_loader_error_t esp_loader_connect_secure_download_mode(esp_loader_connect_args_t *connect_args,
const uint32_t flash_size, const target_chip_t target_chip)
{
s_target_flash_size = flash_size;
s_target = target_chip;
loader_port_enter_bootloader();
RETURN_ON_ERROR(loader_initialize_conn(connect_args));
if (s_target == ESP_UNKNOWN_CHIP) {
RETURN_ON_ERROR(loader_detect_chip(&s_target, &s_reg));
}
if (s_target == ESP8266_CHIP) {
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_flash_begin_cmd(0, 0, 0, 0, s_target);
} else {
uint32_t spi_config;
RETURN_ON_ERROR( loader_read_spi_config(s_target, &spi_config) );
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_spi_attach_cmd(spi_config);
}
return ESP_LOADER_SUCCESS;
}
#endif /* SERIAL_FLASHER_INTERFACE_UART */
static esp_loader_error_t spi_set_data_lengths(size_t mosi_bits, size_t miso_bits)
{
if (mosi_bits > 0) {
RETURN_ON_ERROR( esp_loader_write_register(s_reg->mosi_dlen, mosi_bits - 1) );
}
if (miso_bits > 0) {
RETURN_ON_ERROR( esp_loader_write_register(s_reg->miso_dlen, miso_bits - 1) );
}
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t spi_set_data_lengths_8266(size_t mosi_bits, size_t miso_bits)
{
uint32_t mosi_mask = (mosi_bits == 0) ? 0 : mosi_bits - 1;
uint32_t miso_mask = (miso_bits == 0) ? 0 : miso_bits - 1;
return esp_loader_write_register(s_reg->usr1, (miso_mask << 8) | (mosi_mask << 17));
}
static esp_loader_error_t spi_flash_command(spi_flash_cmd_t cmd, void *data_tx, size_t tx_size, void *data_rx, size_t rx_size)
{
assert(rx_size <= 32); // Reading more than 32 bits back from a SPI flash operation is unsupported
assert(tx_size <= 64); // Writing more than 64 bytes of data with one SPI command is unsupported
uint32_t SPI_USR_CMD = (1 << 31);
uint32_t SPI_USR_MISO = (1 << 28);
uint32_t SPI_USR_MOSI = (1 << 27);
uint32_t SPI_CMD_USR = (1 << 18);
uint32_t CMD_LEN_SHIFT = 28;
// Save SPI configuration
uint32_t old_spi_usr;
uint32_t old_spi_usr2;
RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr, &old_spi_usr) );
RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr2, &old_spi_usr2) );
if (s_target == ESP8266_CHIP) {
RETURN_ON_ERROR( spi_set_data_lengths_8266(tx_size, rx_size) );
} else {
RETURN_ON_ERROR( spi_set_data_lengths(tx_size, rx_size) );
}
uint32_t usr_reg_2 = (7 << CMD_LEN_SHIFT) | cmd;
uint32_t usr_reg = SPI_USR_CMD;
if (rx_size > 0) {
usr_reg |= SPI_USR_MISO;
}
if (tx_size > 0) {
usr_reg |= SPI_USR_MOSI;
}
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, usr_reg) );
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, usr_reg_2 ) );
if (tx_size == 0) {
// clear data register before we read it
RETURN_ON_ERROR( esp_loader_write_register(s_reg->w0, 0) );
} else {
uint32_t *data = (uint32_t *)data_tx;
uint32_t words_to_write = (tx_size + 31) / (8 * 4);
uint32_t data_reg_addr = s_reg->w0;
while (words_to_write--) {
uint32_t word = *data++;
RETURN_ON_ERROR( esp_loader_write_register(data_reg_addr, word) );
data_reg_addr += 4;
}
}
RETURN_ON_ERROR( esp_loader_write_register(s_reg->cmd, SPI_CMD_USR) );
uint32_t trials = 10;
while (trials--) {
uint32_t cmd_reg;
RETURN_ON_ERROR( esp_loader_read_register(s_reg->cmd, &cmd_reg) );
if ((cmd_reg & SPI_CMD_USR) == 0) {
break;
}
}
if (trials == 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
RETURN_ON_ERROR( esp_loader_read_register(s_reg->w0, data_rx) );
// Restore SPI configuration
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, old_spi_usr) );
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, old_spi_usr2) );
return ESP_LOADER_SUCCESS;
}
static uint32_t calc_erase_size(const target_chip_t target, const uint32_t offset,
const uint32_t image_size)
{
if (target != ESP8266_CHIP || esp_stub_get_running()) {
return image_size;
} else {
/* Needed to fix a bug in the ESP8266 ROM */
const uint32_t sectors_per_block = 16U;
const uint32_t sector_size = 4096U;
const uint32_t num_sectors = (image_size + sector_size - 1) / sector_size;
const uint32_t start_sector = offset / sector_size;
uint32_t head_sectors = sectors_per_block - (start_sector % sectors_per_block);
/* The ROM bug deletes extra num_sectors if we don't cross the block boundary
and extra head_sectors if we do */
if (num_sectors <= head_sectors) {
return ((num_sectors + 1) / 2) * sector_size;
} else {
return (num_sectors - head_sectors) * sector_size;
}
}
}
esp_loader_error_t esp_loader_flash_detect_size(uint32_t *flash_size)
{
typedef struct {
uint8_t id;
uint32_t size;
} size_id_size_pair_t;
/* There is no rule manufacturers have to follow for assigning these parts of the flash ID,
these constants have been taken from esptool source code. */
static const size_id_size_pair_t size_mapping[] = {
{ 0x12, 256 * 1024 },
{ 0x13, 512 * 1024 },
{ 0x14, 1 * 1024 * 1024 },
{ 0x15, 2 * 1024 * 1024 },
{ 0x16, 4 * 1024 * 1024 },
{ 0x17, 8 * 1024 * 1024 },
{ 0x18, 16 * 1024 * 1024 },
{ 0x19, 32 * 1024 * 1024 },
{ 0x1A, 64 * 1024 * 1024 },
{ 0x1B, 128 * 1024 * 1024 },
{ 0x1C, 256 * 1024 * 1024 },
{ 0x20, 64 * 1024 * 1024 },
{ 0x21, 128 * 1024 * 1024 },
{ 0x22, 256 * 1024 * 1024 },
{ 0x32, 256 * 1024 },
{ 0x33, 512 * 1024 },
{ 0x34, 1 * 1024 * 1024 },
{ 0x35, 2 * 1024 * 1024 },
{ 0x36, 4 * 1024 * 1024 },
{ 0x37, 8 * 1024 * 1024 },
{ 0x38, 16 * 1024 * 1024 },
{ 0x39, 32 * 1024 * 1024 },
{ 0x3A, 64 * 1024 * 1024 },
};
uint32_t flash_id = 0;
RETURN_ON_ERROR( spi_flash_command(SPI_FLASH_READ_ID, NULL, 0, &flash_id, 24) );
uint8_t size_id = flash_id >> 16;
// Try finding the size id within supported size ids
for (size_t i = 0; i < sizeof(size_mapping) / sizeof(size_mapping[0]); i++) {
if (size_id == size_mapping[i].id) {
*flash_size = size_mapping[i].size;
return ESP_LOADER_SUCCESS;
}
}
return ESP_LOADER_ERROR_UNSUPPORTED_CHIP;
}
esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size)
{
s_flash_write_size = block_size;
// Both the address and image size must be aligned to 4 bytes
if (offset % 4 != 0 || image_size % 4 != 0) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
/* Flash size will be known in advance if we're in secure download mode or we already read it*/
if (s_target_flash_size == 0) {
if (esp_loader_flash_detect_size(&s_target_flash_size) == ESP_LOADER_SUCCESS) {
if (image_size + offset > s_target_flash_size) {
return ESP_LOADER_ERROR_IMAGE_SIZE;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
RETURN_ON_ERROR(loader_spi_parameters(s_target_flash_size));
} else {
loader_port_debug_print("Flash size detection failed, falling back to default");
s_target_flash_size = DEFAULT_FLASH_SIZE;
}
}
#if MD5_ENABLED
init_md5(offset, image_size);
#endif
bool encryption_in_cmd = encryption_in_begin_flash_cmd(s_target) && !esp_stub_get_running();
const uint32_t erase_size = calc_erase_size(esp_loader_get_target(), offset, image_size);
const uint32_t blocks_to_write = (image_size + block_size - 1) / block_size;
const uint32_t erase_region_timeout_per_mb = 10000;
loader_port_start_timer(timeout_per_mb(erase_size, erase_region_timeout_per_mb));
return loader_flash_begin_cmd(offset, erase_size, block_size, blocks_to_write, encryption_in_cmd);
}
esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size)
{
uint32_t padding_bytes = s_flash_write_size - size;
uint8_t *data = (uint8_t *)payload;
uint32_t padding_index = size;
if (size > s_flash_write_size) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
const uint8_t padding_pattern = 0xFF;
while (padding_bytes--) {
data[padding_index++] = padding_pattern;
}
#if MD5_ENABLED
md5_update(payload, (size + 3) & ~3);
#endif
unsigned int attempt = 0;
esp_loader_error_t result = ESP_LOADER_ERROR_FAIL;
do {
loader_port_start_timer(DEFAULT_TIMEOUT);
result = loader_flash_data_cmd(data, s_flash_write_size);
attempt++;
} while (result != ESP_LOADER_SUCCESS && attempt < SERIAL_FLASHER_WRITE_BLOCK_RETRIES);
return result;
}
esp_loader_error_t esp_loader_flash_finish(bool reboot)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_flash_end_cmd(!reboot);
}
esp_loader_error_t esp_loader_change_transmission_rate_stub(const uint32_t old_transmission_rate,
const uint32_t new_transmission_rate)
{
if (s_target == ESP8266_CHIP || !esp_stub_get_running()) {
return ESP_LOADER_ERROR_UNSUPPORTED_FUNC;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
esp_loader_error_t err = loader_change_baudrate_cmd(new_transmission_rate, old_transmission_rate);
// Wait for the stub to be ready to receive data.
if (err == ESP_LOADER_SUCCESS) {
loader_port_delay_ms(25);
}
return err;
}
static uint32_t byte_popcnt(uint8_t byte)
{
uint32_t cnt = 0;
for (uint32_t bit = 0; bit < 8; bit++) {
cnt += byte & 0x01;
byte >>= 1;
}
return cnt;
}
esp_loader_error_t esp_loader_get_security_info(esp_loader_target_security_info_t *security_info)
{
loader_port_start_timer(SHORT_TIMEOUT);
get_security_info_response_data_t resp;
uint32_t response_received_size = 0;
RETURN_ON_ERROR(loader_get_security_info_cmd(&resp, &response_received_size));
if (response_received_size == sizeof(get_security_info_response_data_t)) {
security_info->target_chip = target_from_chip_id(resp.chip_id);
security_info->eco_version = resp.eco_version;
} else if (response_received_size == sizeof(get_security_info_response_data_t) - 8) {
security_info->target_chip = ESP32S2_CHIP;
security_info->eco_version = 0;
} else {
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
security_info->secure_boot_enabled =
(resp.flags & GET_SECURITY_INFO_SECURE_BOOT_EN) != 0;
security_info->secure_boot_aggressive_revoke_enabled =
(resp.flags & GET_SECURITY_INFO_SECURE_BOOT_AGGRESSIVE_REVOKE) != 0;
security_info->secure_download_mode_enabled =
(resp.flags & GET_SECURITY_INFO_SECURE_DOWNLOAD_ENABLE) != 0;
security_info->secure_boot_revoked_keys[0] =
(resp.flags & GET_SECURITY_INFO_SECURE_BOOT_KEY_REVOKE0) != 0;
security_info->secure_boot_revoked_keys[1] =
(resp.flags & GET_SECURITY_INFO_SECURE_BOOT_KEY_REVOKE1) != 0;
security_info->secure_boot_revoked_keys[2] =
(resp.flags & GET_SECURITY_INFO_SECURE_BOOT_KEY_REVOKE2) != 0;
security_info->jtag_software_disabled =
(resp.flags & GET_SECURITY_INFO_SOFT_DIS_JTAG) != 0;
security_info->jtag_hardware_disabled =
(resp.flags & GET_SECURITY_INFO_HARD_DIS_JTAG) != 0;
security_info->usb_disabled = (resp.flags & GET_SECURITY_INFO_DIS_USB) != 0;
// If the number of set bits in key_purposes is odd, flash is encrypted
uint32_t key_purposes_bit_cnt = 0;
for (size_t byte = 0; byte < sizeof(resp.key_purposes); byte++) {
key_purposes_bit_cnt += byte_popcnt(resp.key_purposes[byte]);
}
security_info->flash_encryption_enabled = key_purposes_bit_cnt % 2;
security_info->dcache_in_uart_download_disabled =
(resp.flags & GET_SECURITY_INFO_DIS_DOWNLOAD_DCACHE) != 0;
security_info->icache_in_uart_download_disabled =
(resp.flags & GET_SECURITY_INFO_DIS_DOWNLOAD_ICACHE) != 0;
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t flash_read_stub(uint8_t *dest, uint32_t address, uint32_t length)
{
uint8_t buf[256]; // Hardcoded for now, decent tradeoff between speed and stack usage
size_t recv_size = 0;
struct MD5Context md5_context;
MD5Init(&md5_context);
// The flasher stub requires reads to be aligned to 4 bytes.
// The solution is to read more than is needed and discard the unecessary bytes.
const uint32_t seek_back_len = address % 4;
address -= seek_back_len;
length += seek_back_len;
const uint32_t overread_len = ROUNDUP(length, 4) - length;
length += overread_len;
loader_port_start_timer(DEFAULT_TIMEOUT);
loader_flash_read_stub_cmd(address, length, sizeof(buf));
uint32_t copy_dest_start = 0;
int32_t remaining = length;
while (remaining > 0) {
loader_port_start_timer(DEFAULT_TIMEOUT);
const uint32_t to_receive = MIN(remaining, sizeof(buf));
RETURN_ON_ERROR(SLIP_receive_packet(buf, to_receive, &recv_size));
if (recv_size != to_receive) {
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
MD5Update(&md5_context, buf, recv_size);
// Handle seek back and overread.
uint32_t copy_start = 0;
uint32_t copy_length = recv_size;
const bool first_read = remaining == length;
if (first_read) {
copy_start += seek_back_len;
copy_length -= seek_back_len;
}
const bool last_read = remaining - recv_size <= 0;
if (last_read) {
copy_length -= overread_len;
}
memcpy(&dest[copy_dest_start], &buf[copy_start], copy_length);
copy_dest_start += copy_length;
remaining -= recv_size;
// Ack by sending back total received byte count
const uint32_t bytes_recv = length - remaining;
loader_port_start_timer(DEFAULT_TIMEOUT);
RETURN_ON_ERROR(SLIP_send_delimiter());
RETURN_ON_ERROR(SLIP_send((const uint8_t *)&bytes_recv, sizeof(bytes_recv)));
RETURN_ON_ERROR(SLIP_send_delimiter());
}
uint8_t md5_calc[16];
MD5Final(md5_calc, &md5_context);
loader_port_start_timer(DEFAULT_TIMEOUT);
uint8_t md5_recv[16];
RETURN_ON_ERROR(SLIP_receive_packet(md5_recv, sizeof(md5_recv), &recv_size));
if (recv_size != sizeof(md5_recv) || memcmp(md5_calc, md5_recv, sizeof(md5_calc))) {
return ESP_LOADER_ERROR_INVALID_MD5;
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t esp_loader_flash_read(uint8_t *dest, uint32_t address, uint32_t length)
{
/* Flash size will be known in advance if we're in secure download mode or we already read it*/
if (s_target_flash_size == 0) {
if (esp_loader_flash_detect_size(&s_target_flash_size) == ESP_LOADER_SUCCESS) {
if (address + length >= s_target_flash_size) {
return ESP_LOADER_ERROR_IMAGE_SIZE;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
RETURN_ON_ERROR(loader_spi_parameters(s_target_flash_size));
} else {
loader_port_debug_print("Flash size detection failed, falling back to default");
s_target_flash_size = DEFAULT_FLASH_SIZE;
}
}
if (esp_stub_get_running()) {
RETURN_ON_ERROR(flash_read_stub(dest, address, length));
} else {
// We read from the ROM in 64B chunks, if we want to read anything in the last 64B
// we need to ensure that the read is aligned to 64B, so we read more than necessary.
const uint32_t seek_back_len = address % READ_FLASH_ROM_DATA_SIZE;
address -= seek_back_len;
length += seek_back_len;
uint32_t copy_dest_start = 0;
int32_t remaining = length;
while (remaining > 0) {
uint8_t buf[READ_FLASH_ROM_DATA_SIZE];
loader_port_start_timer(DEFAULT_TIMEOUT);
RETURN_ON_ERROR(loader_flash_read_rom_cmd(address + length - remaining, buf));
const bool first_read = remaining == length;
size_t to_read = MIN(remaining, sizeof(buf));
if (first_read) {
to_read -= seek_back_len;
memcpy(&dest[0], &buf[seek_back_len], to_read);
} else {
memcpy(&dest[copy_dest_start], &buf[0], to_read);
}
remaining -= READ_FLASH_ROM_DATA_SIZE;
copy_dest_start += to_read;
}
}
return ESP_LOADER_SUCCESS;
}
#endif /* SERIAL_FLASHER_INTERFACE_UART || SERIAL_FLASHER_INTERFACE_USB */
esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size)
{
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
if (esp_stub_get_running()) {
const esp_stub_t *stub = &esp_stub[s_target];
// check we're not going to overwrite a running stub with this data
const uint32_t load_start = offset;
const uint32_t load_end = offset + size;
for (uint32_t seg = 0; seg < sizeof(stub->segments) / sizeof(stub->segments[0]); seg++) {
const uint32_t stub_start = stub->segments[seg].addr;
const uint32_t stub_end = stub->segments[seg].addr + stub->segments[seg].size;
if (load_start < stub_end && load_end > stub_start) {
loader_port_debug_print("Software loader is resident at the requested address, can't load binary at overlapping address range");
return ESP_LOADER_ERROR_INVALID_PARAM;
}
}
}
#endif
uint32_t blocks_to_write = ROUNDUP(size, block_size);
loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB));
return loader_mem_begin_cmd(offset, size, blocks_to_write, block_size);
}
esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size)
{
const uint8_t *data = (const uint8_t *)payload;
unsigned int attempt = 0;
esp_loader_error_t result = ESP_LOADER_ERROR_FAIL;
do {
loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB));
result = loader_mem_data_cmd(data, size);
attempt++;
} while (result != ESP_LOADER_SUCCESS && attempt < SERIAL_FLASHER_WRITE_BLOCK_RETRIES);
return result;
}
esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_mem_end_cmd(entrypoint);
}
#ifndef SERIAL_FLASHER_INTERFACE_SDIO
esp_loader_error_t esp_loader_read_mac(uint8_t *mac)
{
if (s_target == ESP8266_CHIP) {
return ESP_LOADER_ERROR_UNSUPPORTED_CHIP;
}
return loader_read_mac(s_target, mac);
}
esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_read_reg_cmd(address, reg_value);
}
esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_write_reg_cmd(address, reg_value, 0xFFFFFFFF, 0);
}
esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate)
{
if (s_target == ESP8266_CHIP || esp_stub_get_running()) {
return ESP_LOADER_ERROR_UNSUPPORTED_FUNC;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_change_baudrate_cmd(transmission_rate, 0);
}
#endif /* SERIAL_FLASHER_INTERFACE_SDIO */
#if MD5_ENABLED
static void hexify(const uint8_t raw_md5[16], uint8_t hex_md5_out[32])
{
static const uint8_t dec_to_hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
for (int i = 0; i < 16; i++) {
*hex_md5_out++ = dec_to_hex[raw_md5[i] >> 4];
*hex_md5_out++ = dec_to_hex[raw_md5[i] & 0xF];
}
}
esp_loader_error_t esp_loader_flash_verify_known_md5(uint32_t address,
uint32_t size,
const uint8_t *expected_md5)
{
if (s_target == ESP8266_CHIP && !esp_stub_get_running()) {
return ESP_LOADER_ERROR_UNSUPPORTED_FUNC;
}
if (s_target_flash_size == 0) {
if (esp_loader_flash_detect_size(&s_target_flash_size) == ESP_LOADER_SUCCESS) {
loader_port_start_timer(DEFAULT_TIMEOUT);
RETURN_ON_ERROR( loader_spi_parameters(s_target_flash_size) );
} else {
loader_port_debug_print("Flash size detection failed, falling back to default");
s_target_flash_size = DEFAULT_FLASH_SIZE;
}
}
if (address + size > s_target_flash_size) {
return ESP_LOADER_ERROR_IMAGE_SIZE;
}
/* Zero termination require 1 byte */
uint8_t received_md5[MAX(MD5_SIZE_ROM, MD5_SIZE_STUB) + 1] = {0};
loader_port_start_timer(timeout_per_mb(size, MD5_TIMEOUT_PER_MB));
RETURN_ON_ERROR(loader_md5_cmd(address, size, received_md5));
if (esp_stub_get_running()) {
// Convert the received MD5 to hex, because stub returns it as 16 raw data bytes
uint8_t rec_md5_hex[MAX(MD5_SIZE_ROM, MD5_SIZE_STUB) + 1] = {0};
hexify(received_md5, rec_md5_hex);
memcpy(received_md5, rec_md5_hex, MD5_SIZE_ROM);
}
bool md5_match = memcmp(expected_md5, received_md5, MD5_SIZE_ROM) == 0;
if (!md5_match) {
loader_port_debug_print("Error: MD5 checksum does not match");
loader_port_debug_print("Expected:");
loader_port_debug_print((char *)expected_md5);
loader_port_debug_print("Actual:");
loader_port_debug_print((char *)received_md5);
return ESP_LOADER_ERROR_INVALID_MD5;
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t esp_loader_flash_verify(void)
{
uint8_t raw_md5[16] = {0};
/* Zero termination require 1 byte */
uint8_t hex_md5[MAX(MD5_SIZE_ROM, MD5_SIZE_STUB) + 1] = {0};
md5_final(raw_md5);
hexify(raw_md5, hex_md5);
return esp_loader_flash_verify_known_md5(s_start_address, s_image_size, hex_md5);
}
#endif
void esp_loader_reset_target(void)
{
esp_stub_set_running(false);
loader_port_reset_target();
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,353 @@
/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "esp_targets.h"
#include <stddef.h>
#define MAX_MAGIC_VALUES 4
typedef esp_loader_error_t (*read_spi_config_t)(uint32_t efuse_base, uint32_t *spi_config);
typedef struct {
target_registers_t regs;
uint32_t efuse_base;
uint32_t chip_magic_value[MAX_MAGIC_VALUES];
uint32_t mac_efuse_offset;
uint32_t chip_id;
read_spi_config_t read_spi_config;
bool encryption_in_begin_flash_cmd;
} esp_target_t;
// This ROM address has a different value on each chip model
#define CHIP_DETECT_MAGIC_REG_ADDR 0x40001000
#define ESP8266_SPI_REG_BASE 0x60000200
#define ESP32S2_SPI_REG_BASE 0x3f402000
#define ESP32H2_SPI_REG_BASE 0x60003000
#define ESP32C6_SPI_REG_BASE 0x60003000
#define ESP32xx_SPI_REG_BASE 0x60002000
#define ESP32_SPI_REG_BASE 0x3ff42000
#define CHIP_ID_NONE 0xFF
static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config);
static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config);
static esp_loader_error_t spi_config_unsupported(uint32_t efuse_base, uint32_t *spi_config);
static const esp_target_t esp_target[ESP_MAX_CHIP] = {
// ESP8266
{
.regs = {
.cmd = ESP8266_SPI_REG_BASE + 0x00,
.usr = ESP8266_SPI_REG_BASE + 0x1c,
.usr1 = ESP8266_SPI_REG_BASE + 0x20,
.usr2 = ESP8266_SPI_REG_BASE + 0x24,
.w0 = ESP8266_SPI_REG_BASE + 0x40,
.mosi_dlen = 0,
.miso_dlen = 0,
},
.efuse_base = 0, // Not used
.chip_magic_value = { 0xfff0c101, 0, 0, 0 },
.read_spi_config = NULL, // Not used
.mac_efuse_offset = 0, // Not used
.encryption_in_begin_flash_cmd = false,
.chip_id = CHIP_ID_NONE,
},
// ESP32
{
.regs = {
.cmd = ESP32_SPI_REG_BASE + 0x00,
.usr = ESP32_SPI_REG_BASE + 0x1c,
.usr1 = ESP32_SPI_REG_BASE + 0x20,
.usr2 = ESP32_SPI_REG_BASE + 0x24,
.w0 = ESP32_SPI_REG_BASE + 0x80,
.mosi_dlen = ESP32_SPI_REG_BASE + 0x28,
.miso_dlen = ESP32_SPI_REG_BASE + 0x2c,
},
.efuse_base = 0x3ff5A000,
.chip_magic_value = { 0x00f01d83, 0, 0, 0 },
.read_spi_config = spi_config_esp32,
.mac_efuse_offset = 0x04,
.encryption_in_begin_flash_cmd = false,
.chip_id = 0,
},
// ESP32S2
{
.regs = {
.cmd = ESP32S2_SPI_REG_BASE + 0x00,
.usr = ESP32S2_SPI_REG_BASE + 0x18,
.usr1 = ESP32S2_SPI_REG_BASE + 0x1c,
.usr2 = ESP32S2_SPI_REG_BASE + 0x20,
.w0 = ESP32S2_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32S2_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32S2_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x3f41A000,
.chip_magic_value = { 0x000007c6, 0, 0, 0},
.read_spi_config = spi_config_esp32xx,
.mac_efuse_offset = 0x44,
.encryption_in_begin_flash_cmd = true,
.chip_id = 2,
},
// ESP32C3
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60008800,
.chip_magic_value = { 0x6921506f, 0x1b31506f, 0x4881606F, 0x4361606F },
.read_spi_config = spi_config_esp32xx,
.mac_efuse_offset = 0x44,
.encryption_in_begin_flash_cmd = true,
.chip_id = 5,
},
// ESP32S3
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60007000,
.chip_magic_value = { 0x00000009, 0, 0, 0 },
.read_spi_config = spi_config_esp32xx,
.mac_efuse_offset = 0x44,
.encryption_in_begin_flash_cmd = true,
.chip_id = 9,
},
// ESP32C2
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60008800,
.chip_magic_value = { 0x6f51306f, 0x7c41a06f, 0, 0 },
.read_spi_config = spi_config_unsupported,
.mac_efuse_offset = 0x40,
.encryption_in_begin_flash_cmd = true,
.chip_id = 12,
},
// Reserved for future use
{
.chip_id = CHIP_ID_NONE,
},
// ESP32H2
{
.regs = {
.cmd = ESP32H2_SPI_REG_BASE + 0x00,
.usr = ESP32H2_SPI_REG_BASE + 0x18,
.usr1 = ESP32H2_SPI_REG_BASE + 0x1c,
.usr2 = ESP32H2_SPI_REG_BASE + 0x20,
.w0 = ESP32H2_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32H2_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32H2_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x600B0800,
.chip_magic_value = { 0xd7b73e80, 0, 0, 0 },
.read_spi_config = spi_config_unsupported,
.mac_efuse_offset = 0x44,
.encryption_in_begin_flash_cmd = true,
.chip_id = 16,
},
// ESP32C6
{
.regs = {
.cmd = ESP32C6_SPI_REG_BASE + 0x00,
.usr = ESP32C6_SPI_REG_BASE + 0x18,
.usr1 = ESP32C6_SPI_REG_BASE + 0x1c,
.usr2 = ESP32C6_SPI_REG_BASE + 0x20,
.w0 = ESP32C6_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32C6_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32C6_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x600B0800,
.chip_magic_value = { 0x2CE0806F, 0, 0, 0 },
.read_spi_config = spi_config_unsupported,
.mac_efuse_offset = 0x44,
.encryption_in_begin_flash_cmd = true,
.chip_id = 13,
},
};
const target_registers_t *get_esp_target_data(target_chip_t chip)
{
return (const target_registers_t *)&esp_target[chip];
}
esp_loader_error_t loader_detect_chip(target_chip_t *target_chip, const target_registers_t **target_data)
{
#if (defined SERIAL_FLASHER_INTERFACE_UART) || (defined SERIAL_FLASHER_INTERFACE_USB)
/* First, attempt to get the target info using GET_SECURITY_INFO command.
This won't work if the target does not support the command. */
esp_loader_target_security_info_t security_info;
if (esp_loader_get_security_info(&security_info) == ESP_LOADER_SUCCESS) {
*target_chip = security_info.target_chip;
*target_data = (target_registers_t *)&esp_target[security_info.target_chip];
return ESP_LOADER_SUCCESS;
}
#endif /* SERIAL_FLASHER_INTERFACE_UART || SERIAL_FLASHER_INTERFACE_USB */
uint32_t magic_value;
RETURN_ON_ERROR( esp_loader_read_register(CHIP_DETECT_MAGIC_REG_ADDR, &magic_value) );
for (int chip = 0; chip < ESP_MAX_CHIP; chip++) {
for (int index = 0; index < MAX_MAGIC_VALUES; index++) {
if (magic_value == esp_target[chip].chip_magic_value[index]) {
*target_chip = (target_chip_t)chip;
*target_data = (target_registers_t *)&esp_target[chip];
return ESP_LOADER_SUCCESS;
}
}
}
return ESP_LOADER_ERROR_INVALID_TARGET;
}
esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config)
{
const esp_target_t *target = &esp_target[target_chip];
return target->read_spi_config(target->efuse_base, spi_config);
}
esp_loader_error_t loader_read_mac(const target_chip_t target_code, uint8_t *mac)
{
const esp_target_t *target = &esp_target[target_code];
uint32_t part1;
uint32_t part2;
RETURN_ON_ERROR(esp_loader_read_register(target->efuse_base + target->mac_efuse_offset, &part1));
RETURN_ON_ERROR(esp_loader_read_register(target->efuse_base + target->mac_efuse_offset + sizeof(uint32_t), &part2));
mac[0] = (part2 >> 8) & 0xff;
mac[1] = (part2 >> 0) & 0xff;
mac[2] = (part1 >> 24) & 0xff;
mac[3] = (part1 >> 16) & 0xff;
mac[4] = (part1 >> 8) & 0xff;
mac[5] = (part1 >> 0) & 0xff;
return ESP_LOADER_SUCCESS;
}
static inline uint32_t efuse_word_addr(uint32_t efuse_base, uint32_t n)
{
return efuse_base + (n * 4);
}
// 30->GPIO32 | 31->GPIO33
static inline uint8_t adjust_pin_number(uint8_t num)
{
return (num >= 30) ? num + 2 : num;
}
static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config)
{
*spi_config = 0;
uint32_t reg5, reg3;
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 5), &reg5) );
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 3), &reg3) );
uint32_t pins = reg5 & 0xfffff;
if (pins == 0 || pins == 0xfffff) {
return ESP_LOADER_SUCCESS;
}
uint8_t clk = adjust_pin_number( (pins >> 0) & 0x1f );
uint8_t q = adjust_pin_number( (pins >> 5) & 0x1f );
uint8_t d = adjust_pin_number( (pins >> 10) & 0x1f );
uint8_t cs = adjust_pin_number( (pins >> 15) & 0x1f );
uint8_t hd = adjust_pin_number( (reg3 >> 4) & 0x1f );
if (clk == cs || clk == d || clk == q || q == cs || q == d || q == d) {
return ESP_LOADER_SUCCESS;
}
*spi_config = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk;
return ESP_LOADER_SUCCESS;
}
// Applies for esp32s2, esp32c3 and esp32c3
static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config)
{
*spi_config = 0;
uint32_t reg1, reg2;
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 18), &reg1) );
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 19), &reg2) );
uint32_t pins = ((reg1 >> 16) | ((reg2 & 0xfffff) << 16)) & 0x3fffffff;
if (pins == 0 || pins == 0xffffffff) {
return ESP_LOADER_SUCCESS;
}
*spi_config = pins;
return ESP_LOADER_SUCCESS;
}
// Some newer chips like the esp32c6 do not support configurable SPI
static esp_loader_error_t spi_config_unsupported(uint32_t efuse_base, uint32_t *spi_config)
{
(void)(efuse_base);
*spi_config = 0;
return ESP_LOADER_SUCCESS;
}
bool encryption_in_begin_flash_cmd(const target_chip_t target)
{
return esp_target[target].encryption_in_begin_flash_cmd;
}
target_chip_t target_from_chip_id(const uint32_t chip_id)
{
for (size_t chip = 0; chip < ESP_MAX_CHIP; chip++) {
if (chip_id == esp_target[chip].chip_id) {
return (target_chip_t)chip;
}
}
return ESP_UNKNOWN_CHIP;
}

View File

@ -0,0 +1,262 @@
/*
* MD5 hash implementation and interface functions
* Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "md5_hash.h"
#include <stdlib.h>
#include <string.h>
static void MD5Transform(uint32_t buf[4], uint32_t const in[16]);
/* ===== start - public domain MD5 implementation ===== */
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
#ifndef WORDS_BIGENDIAN
#define byteReverse(buf, len) /* Nothing */
#else
/*
* Note: this code is harmless on little-endian machines.
*/
static void byteReverse(unsigned char *buf, unsigned longs)
{
uint32_t t;
do {
t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(uint32_t *) buf = t;
buf += 4;
} while (--longs);
}
#endif
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void MD5Init(struct MD5Context *ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
/*
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len)
{
uint32_t t;
/* Update bitcount */
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) {
ctx->bits[1]++; /* Carry from low to high */
}
ctx->bits[1] += len >> 29;
t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
/* Handle any leading odd-sized chunks */
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
/* Process data in 64-byte chunks */
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
memcpy(ctx->in, buf, len);
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
{
unsigned count;
unsigned char *p;
/* Compute number of bytes mod 64 */
count = (ctx->bits[0] >> 3) & 0x3F;
/* Set the first char of padding to 0x80. This is safe since there is
always at least one byte free */
p = ctx->in + count;
*p++ = 0x80;
/* Bytes of padding needed to make 64 bytes */
count = 64 - 1 - count;
/* Pad out to 56 mod 64 */
if (count < 8) {
/* Two lots of padding: Pad the first block to 64 bytes */
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
/* Now fill the next block with 56 bytes */
memset(ctx->in, 0, 56);
} else {
/* Pad block to 56 bytes */
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
/* Append length in bits and transform */
((uint32_t *) ctx->in)[14] = ctx->bits[0];
((uint32_t *) ctx->in)[15] = ctx->bits[1];
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset(ctx, 0, sizeof(struct MD5Context)); /* In case it's sensitive */
}
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
* reflect the addition of 16 longwords of new data. MD5Update blocks
* the data and converts bytes into longwords for this routine.
*/
static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
{
register uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
/* ===== end - public domain MD5 implementation ===== */

View File

@ -0,0 +1,446 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "protocol.h"
#include "protocol_prv.h"
#include "esp_loader_io.h"
#include "esp_stubs.h"
#include <stddef.h>
#include <string.h>
#define CMD_SIZE(cmd) ( sizeof(cmd) - sizeof(command_common_t) )
static uint32_t s_sequence_number = 0;
static uint8_t compute_checksum(const uint8_t *data, uint32_t size)
{
uint8_t checksum = 0xEF;
while (size--) {
checksum ^= *data++;
}
return checksum;
}
void log_loader_internal_error(error_code_t error)
{
switch (error) {
case INVALID_CRC: loader_port_debug_print("Error: INVALID_CRC"); break;
case INVALID_COMMAND: loader_port_debug_print("Error: INVALID_COMMAND"); break;
case COMMAND_FAILED: loader_port_debug_print("Error: COMMAND_FAILED"); break;
case FLASH_WRITE_ERR: loader_port_debug_print("Error: FLASH_WRITE_ERR"); break;
case FLASH_READ_ERR: loader_port_debug_print("Error: FLASH_READ_ERR"); break;
case READ_LENGTH_ERR: loader_port_debug_print("Error: READ_LENGTH_ERR"); break;
case DEFLATE_ERROR: loader_port_debug_print("Error: DEFLATE_ERROR"); break;
default: loader_port_debug_print("Error: UNKNOWN ERROR"); break;
}
}
esp_loader_error_t loader_flash_begin_cmd(uint32_t offset,
uint32_t erase_size,
uint32_t block_size,
uint32_t blocks_to_write,
bool encryption)
{
flash_begin_command_t flash_begin_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_BEGIN,
.size = CMD_SIZE(flash_begin_cmd) - (encryption ? 0 : sizeof(uint32_t)),
.checksum = 0
},
.erase_size = erase_size,
.packet_count = blocks_to_write,
.packet_size = block_size,
.offset = offset,
.encrypted = 0
};
s_sequence_number = 0;
const send_cmd_config cmd_config = {
.cmd = &flash_begin_cmd,
.cmd_size = sizeof(flash_begin_cmd) - (encryption ? 0 : sizeof(uint32_t)),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size)
{
data_command_t data_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_DATA,
.size = CMD_SIZE(data_cmd) + size,
.checksum = compute_checksum(data, size)
},
.data_size = size,
.sequence_number = s_sequence_number++,
};
const send_cmd_config cmd_config = {
.cmd = &data_cmd,
.cmd_size = sizeof(data_cmd),
.data = data,
.data_size = size,
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader)
{
flash_end_command_t end_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_END,
.size = CMD_SIZE(end_cmd),
.checksum = 0
},
.stay_in_loader = stay_in_loader
};
const send_cmd_config cmd_config = {
.cmd = &end_cmd,
.cmd_size = sizeof(end_cmd)
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_flash_read_rom_cmd(const uint32_t address, uint8_t *data)
{
const flash_read_rom_cmd flash_read_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = READ_FLASH_ROM,
.size = CMD_SIZE(flash_read_cmd),
.checksum = 0
},
.address = address,
.size = READ_FLASH_ROM_DATA_SIZE,
};
const send_cmd_config cmd_config = {
.cmd = &flash_read_cmd,
.cmd_size = sizeof(flash_read_cmd),
.resp_data = data,
.resp_data_size = READ_FLASH_ROM_DATA_SIZE,
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_flash_read_stub_cmd(const uint32_t address, const uint32_t size,
const uint32_t size_per_packet)
{
const flash_read_stub_cmd flash_read_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = READ_FLASH_STUB,
.size = CMD_SIZE(flash_read_cmd),
.checksum = 0
},
.address = address,
.total_size = size,
.packet_data_size = size_per_packet,
.max_inflight_packets = 1,
};
const send_cmd_config cmd_config = {
.cmd = &flash_read_cmd,
.cmd_size = sizeof(flash_read_cmd),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_sync_cmd(void)
{
sync_command_t sync_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SYNC,
.size = CMD_SIZE(sync_cmd),
.checksum = 0
},
.sync_sequence = {
0x07, 0x07, 0x12, 0x20,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
}
};
const send_cmd_config cmd_config = {
.cmd = &sync_cmd,
.cmd_size = sizeof(sync_cmd)
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_spi_attach_cmd(uint32_t config)
{
spi_attach_command_t attach_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_ATTACH,
.size = CMD_SIZE(attach_cmd),
.checksum = 0
},
.configuration = config,
.zero = 0
};
const send_cmd_config cmd_config = {
.cmd = &attach_cmd,
.cmd_size = esp_stub_get_running() ? sizeof(attach_cmd) - sizeof(attach_cmd.zero) : sizeof(attach_cmd),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out)
{
spi_flash_md5_command_t md5_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_FLASH_MD5,
.size = CMD_SIZE(md5_cmd),
.checksum = 0
},
.address = address,
.size = size,
.reserved_0 = 0,
.reserved_1 = 0
};
const send_cmd_config cmd_config = {
.cmd = &md5_cmd,
.cmd_size = sizeof(md5_cmd),
.resp_data = md5_out,
.resp_data_size = esp_stub_get_running() ? MD5_SIZE_STUB : MD5_SIZE_ROM,
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_spi_parameters(uint32_t total_size)
{
write_spi_command_t spi_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_SET_PARAMS,
.size = 24,
.checksum = 0
},
.id = 0,
.total_size = total_size,
.block_size = 64 * 1024,
.sector_size = 4 * 1024,
.page_size = 0x100,
.status_mask = 0xFFFF,
};
const send_cmd_config cmd_config = {
.cmd = &spi_cmd,
.cmd_size = sizeof(spi_cmd),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size)
{
mem_begin_command_t mem_begin_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_BEGIN,
.size = CMD_SIZE(mem_begin_cmd),
.checksum = 0
},
.total_size = size,
.blocks = blocks_to_write,
.block_size = block_size,
.offset = offset
};
s_sequence_number = 0;
const send_cmd_config cmd_config = {
.cmd = &mem_begin_cmd,
.cmd_size = sizeof(mem_begin_cmd),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size)
{
data_command_t data_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_DATA,
.size = CMD_SIZE(data_cmd) + size,
.checksum = compute_checksum(data, size)
},
.data_size = size,
.sequence_number = s_sequence_number++,
};
const send_cmd_config cmd_config = {
.cmd = &data_cmd,
.cmd_size = sizeof(data_cmd),
.data = data,
.data_size = size,
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint)
{
mem_end_command_t end_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_END,
.size = CMD_SIZE(end_cmd),
},
.stay_in_loader = (entrypoint == 0),
.entry_point_address = entrypoint
};
const send_cmd_config cmd_config = {
.cmd = &end_cmd,
.cmd_size = sizeof(end_cmd),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value,
uint32_t mask, uint32_t delay_us)
{
write_reg_command_t write_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = WRITE_REG,
.size = CMD_SIZE(write_cmd),
.checksum = 0
},
.address = address,
.value = value,
.mask = mask,
.delay_us = delay_us
};
const send_cmd_config cmd_config = {
.cmd = &write_cmd,
.cmd_size = sizeof(write_cmd),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg)
{
read_reg_command_t read_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = READ_REG,
.size = CMD_SIZE(read_cmd),
.checksum = 0
},
.address = address,
};
const send_cmd_config cmd_config = {
.cmd = &read_cmd,
.cmd_size = sizeof(read_cmd),
.reg_value = reg,
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_change_baudrate_cmd(uint32_t new_baudrate, uint32_t old_baudrate)
{
change_baudrate_command_t baudrate_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = CHANGE_BAUDRATE,
.size = CMD_SIZE(baudrate_cmd),
.checksum = 0
},
.new_baudrate = new_baudrate,
.old_baudrate = old_baudrate
};
const send_cmd_config cmd_config = {
.cmd = &baudrate_cmd,
.cmd_size = sizeof(baudrate_cmd),
};
return send_cmd(&cmd_config);
}
esp_loader_error_t loader_get_security_info_cmd(get_security_info_response_data_t *response,
uint32_t *response_recv_size)
{
const get_security_info_command_t get_security_info_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = GET_SECURITY_INFO,
.size = CMD_SIZE(get_security_info_cmd),
.checksum = 0
},
};
const send_cmd_config cmd_config = {
.cmd = &get_security_info_cmd,
.cmd_size = sizeof(get_security_info_cmd),
.resp_data = response,
.resp_data_size = sizeof(get_security_info_response_data_t),
.resp_data_recv_size = response_recv_size,
};
return send_cmd(&cmd_config);
}
__attribute__ ((weak)) void loader_port_debug_print(const char *str)
{
(void) str;
}

View File

@ -0,0 +1,157 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "protocol.h"
#include "protocol_prv.h"
#include "esp_loader_io.h"
#include "esp_stubs.h"
#include "slip.h"
#include <stddef.h>
#include <string.h>
static esp_loader_error_t check_response(const send_cmd_config *config);
esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args)
{
esp_loader_error_t err;
int32_t trials = connect_args->trials;
do {
loader_port_start_timer(connect_args->sync_timeout);
err = loader_sync_cmd();
if (err == ESP_LOADER_ERROR_TIMEOUT) {
if (--trials == 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
loader_port_delay_ms(100);
} else if (err != ESP_LOADER_SUCCESS) {
return err;
}
} while (err != ESP_LOADER_SUCCESS);
return err;
}
esp_loader_error_t loader_run_stub(target_chip_t target)
{
esp_loader_error_t err;
const esp_stub_t *stub = &esp_stub[target];
// Download segments
for (uint32_t seg = 0; seg < sizeof(stub->segments) / sizeof(stub->segments[0]); seg++) {
err = esp_loader_mem_start(stub->segments[seg].addr, stub->segments[seg].size, ESP_RAM_BLOCK);
if (err != ESP_LOADER_SUCCESS) {
return err;
}
size_t remain_size = stub->segments[seg].size;
uint8_t *data_pos = stub->segments[seg].data;
while (remain_size > 0) {
size_t data_size = MIN(ESP_RAM_BLOCK, remain_size);
err = esp_loader_mem_write(data_pos, data_size);
if (err != ESP_LOADER_SUCCESS) {
return err;
}
data_pos += data_size;
remain_size -= data_size;
}
}
err = esp_loader_mem_finish(stub->header.entrypoint);
if (err != ESP_LOADER_SUCCESS) {
return err;
}
// stub loader sends a custom SLIP packet of the sequence OHAI
uint8_t buff[4];
size_t recv_size = 0;
err = SLIP_receive_packet(buff, sizeof(buff) / sizeof(buff[0]), &recv_size);
if (err != ESP_LOADER_SUCCESS) {
return err;
} else if (recv_size != sizeof(buff) || memcmp(buff, "OHAI", sizeof(buff) / sizeof(buff[0]))) {
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
esp_stub_set_running(true);
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t send_cmd(const send_cmd_config *config)
{
RETURN_ON_ERROR(SLIP_send_delimiter());
RETURN_ON_ERROR(SLIP_send((const uint8_t *)config->cmd, config->cmd_size));
if (config->data != NULL && config->data_size != 0) {
RETURN_ON_ERROR(SLIP_send((const uint8_t *)config->data, config->data_size));
}
RETURN_ON_ERROR(SLIP_send_delimiter());
command_t command = ((const command_common_t *)config->cmd)->command;
const uint8_t response_cnt = command == SYNC ? 8 : 1;
for (uint8_t recv_cnt = 0; recv_cnt < response_cnt; recv_cnt++) {
RETURN_ON_ERROR(check_response(config));
}
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t check_response(const send_cmd_config *config)
{
uint8_t buf[sizeof(common_response_t) + sizeof(response_status_t) + MAX_RESP_DATA_SIZE];
common_response_t *response = (common_response_t *)&buf[0];
command_t command = ((const command_common_t *)config->cmd)->command;
// If the command has fixed response data size, require all of it to be received
uint32_t minimum_packet_recv = sizeof(common_response_t) + sizeof(response_status_t);
if (config->resp_data_recv_size == NULL) {
minimum_packet_recv += config->resp_data_size;
}
size_t packet_recv = 0;
do {
RETURN_ON_ERROR(SLIP_receive_packet(buf,
sizeof(common_response_t) + sizeof(response_status_t) + config->resp_data_size,
&packet_recv));
} while ((response->direction != READ_DIRECTION) || (response->command != command) ||
packet_recv < minimum_packet_recv);
response_status_t *status = (response_status_t *)&buf[packet_recv - sizeof(response_status_t)];
if (status->failed) {
log_loader_internal_error(status->error);
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
if (config->reg_value != NULL) {
*config->reg_value = response->value;
}
if (config->resp_data != NULL) {
const size_t resp_data_size = packet_recv - sizeof(common_response_t) - sizeof(response_status_t);
memcpy(config->resp_data, &buf[sizeof(common_response_t)], resp_data_size);
if (config->resp_data_recv_size != NULL) {
*config->resp_data_recv_size = resp_data_size;
}
}
return ESP_LOADER_SUCCESS;
}

View File

@ -0,0 +1,123 @@
/* Copyright 2020-2024 Espressif Systems (Shanghai) CO LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "slip.h"
#include "esp_loader_io.h"
static const uint8_t DELIMITER = 0xC0;
static const uint8_t C0_REPLACEMENT[2] = {0xDB, 0xDC};
static const uint8_t DB_REPLACEMENT[2] = {0xDB, 0xDD};
static inline esp_loader_error_t peripheral_read(uint8_t *buff, const size_t size)
{
return loader_port_read(buff, size, loader_port_remaining_time());
}
static inline esp_loader_error_t peripheral_write(const uint8_t *buff, const size_t size)
{
return loader_port_write(buff, size, loader_port_remaining_time());
}
esp_loader_error_t SLIP_receive_packet(uint8_t *buff, const size_t max_size, size_t *recv_size)
{
uint8_t ch;
// Wait for delimiter
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch != DELIMITER);
// Workaround: bootloader sends two dummy(0xC0) bytes after response when baud rate is changed.
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch == DELIMITER);
buff[0] = ch;
// Receive either until either delimiter or maximum receive size
for (size_t i = 1; i < max_size; i++) {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
if (ch == 0xDB) {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
if (ch == 0xDC) {
buff[i] = 0xC0;
} else if (ch == 0xDD) {
buff[i] = 0xDB;
} else {
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
} else if (ch == DELIMITER) {
*recv_size = i;
return ESP_LOADER_SUCCESS;
} else {
buff[i] = ch;
}
}
// Wait for delimiter if we already reached max receive size
// This enables us to ignore unsupported or unecessary packet data instead of failing
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch != DELIMITER);
*recv_size = max_size;
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_send(const uint8_t *data, const size_t size)
{
uint32_t to_write = 0; // Bytes ready to write as they are
uint32_t written = 0; // Bytes already written
for (uint32_t i = 0; i < size; i++) {
if (data[i] != 0xC0 && data[i] != 0xDB) {
to_write++; // Queue this byte for writing
continue;
}
// We have a byte that needs encoding, write the queue first
if (to_write > 0) {
RETURN_ON_ERROR( peripheral_write(&data[written], to_write) );
}
// Write the encoded byte
if (data[i] == 0xC0) {
RETURN_ON_ERROR( peripheral_write(C0_REPLACEMENT, 2) );
} else {
RETURN_ON_ERROR( peripheral_write(DB_REPLACEMENT, 2) );
}
// Update to start again after the encoded byte
written = i + 1;
to_write = 0;
}
// Write the rest of the bytes that didn't need encoding
if (to_write > 0) {
RETURN_ON_ERROR( peripheral_write(&data[written], to_write) );
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_send_delimiter(void)
{
return peripheral_write(&DELIMITER, 1);
}

60
main/Kconfig.projbuild Normal file
View File

@ -0,0 +1,60 @@
menu "ESP serial flasher"
config SERIAL_FLASHER_MD5_ENABLED
bool "Enable MD5 check"
default y
help
Select this option to enable MD5 hashsum check after flashing.
choice SERIAL_FLASHER_INTERFACE
prompt "Hardware interface to use for firmware download"
default SERIAL_FLASHER_INTERFACE_UART
help
esp-serial-flasher can work with UART and SPI interfaces.
config SERIAL_FLASHER_INTERFACE_UART
bool "UART"
config SERIAL_FLASHER_INTERFACE_SPI
bool "SPI (Only supports downloading to RAM)"
config SERIAL_FLASHER_INTERFACE_USB
bool "USB"
config SERIAL_FLASHER_INTERFACE_SDIO
bool "SDIO (Experimental, Only supports downloading to RAM)"
endchoice
config SERIAL_FLASHER_RESET_HOLD_TIME_MS
int "Time for which the reset pin is asserted when doing a hard reset"
default 100
config SERIAL_FLASHER_BOOT_HOLD_TIME_MS
int "Time for which the boot pin is asserted when doing a hard reset"
default 50
config SERIAL_FLASHER_DEBUG_TRACE
bool "Enable debug tracing output (only transfer data tracing is supported at the time)"
default n
config SERIAL_FLASHER_WRITE_BLOCK_RETRIES
int "Number of retries when writing blocks either to target flash or RAM"
default 3
config SERIAL_FLASHER_RESET_INVERT
bool "Invert reset signal"
default n
depends on SERIAL_FLASHER_INTERFACE_UART
help
Enable this option if there is an inverting connection between
the output of the serial-flasher and the reset pin of the ESP chip.
config SERIAL_FLASHER_BOOT_INVERT
bool "Invert boot signal"
default n
depends on SERIAL_FLASHER_INTERFACE_UART
help
Enable this option if there is an inverting connection between
the output of the serial-flasher and the boot pin of the ESP chip.
endmenu

View File

@ -25,6 +25,12 @@
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include "esp32_port.h"
#include "esp_loader.h"
#include "example_common.h"
#include "driver/uart.h"
#include "driver/gpio.h"
static const char *TAG = "uart_events";
#define EXAMPLE_ESP_WIFI_SSID "RONGTA"
@ -405,7 +411,7 @@ void app_main(void)
/* Configure parameters of an UART driver,
* communication pins and install the driver */
uart_config_t uart_config = {
.baud_rate = 1500000,
.baud_rate = 115200,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
@ -416,12 +422,35 @@ void app_main(void)
//Install UART driver, and get the queue.
uart_driver_install(EX_UART_NUM, BUF_SIZE * 2, BUF_SIZE * 2, 20, &uart0_queue, 0);
uart_param_config(EX_UART_NUM, &uart_config);
xTaskCreate(echo_task, "USB SERIAL JTAG_echo_task", ECHO_TASK_STACK_SIZE, NULL, 10, NULL);
// xTaskCreate(echo_task, "USB SERIAL JTAG_echo_task", ECHO_TASK_STACK_SIZE, NULL, 10, NULL);
//Create a task to handler UART event from ISR
xTaskCreate(uart_event_task, "uart_event_task", 2048, NULL, 12, NULL);
xTaskCreate(uart_event_task, "uart_event_task", 2048*10, NULL, 12, NULL);
// ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
// wifi_init_sta();
// xTaskCreate(tcp_server_task, "tcp_server", 4096, (void*)AF_INET, 5, NULL);
const loader_esp32_config_t config = {
.baud_rate = 115200,
.uart_port = UART_NUM_1,
.uart_rx_pin = GPIO_NUM_5,
.uart_tx_pin = GPIO_NUM_4,
.reset_trigger_pin = GPIO_NUM_2,
.gpio0_trigger_pin = GPIO_NUM_1,
};
if (loader_port_esp32_init(&config) != ESP_LOADER_SUCCESS) {
ESP_LOGE(TAG, "serial initialization failed.");
return;
}
if (connect_to_target(230400) == ESP_LOADER_SUCCESS) {
ESP_LOGI(TAG, "connect_to_target initialization ESP_LOADER_success.");
}else{
ESP_LOGE(TAG, "connect_to_target initialization failed.");
}
}

639
sdkconfig

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff