diff --git a/armsrc/CMakeLists.txt b/armsrc/CMakeLists.txt index 530fbba0a..a8660e61c 100644 --- a/armsrc/CMakeLists.txt +++ b/armsrc/CMakeLists.txt @@ -51,6 +51,7 @@ set(INC_DIRS ../common_arm/sys ../common_arm/fpga ../common_arm/wdt + ../common_arm/bwm ../common_fpga ../common ../common/lz4 @@ -187,6 +188,12 @@ else () set(SRC_FPC) endif () +if ("${APP_CFLAGS}" MATCHES "WITH_BWM_FORWARD") + set(SRC_BWM bwm_uart_at32.c bwm_forward.c bwm_wifi.c ../common_arm/bwm/bwm_frame.c) +else () + set(SRC_BWM) +endif () + # BWM charger (AW32001) + fuel gauge (BQ27427), incl. the optional low-batt beep if ("${APP_CFLAGS}" MATCHES "WITH_BWM_STATUS" OR "${APP_CFLAGS}" MATCHES "WITH_BWM_CHARGERKICK") set(SRC_BWM_CHARGER bwm_charger.c) @@ -271,6 +278,7 @@ set(THUMBSRC ${SRC_FLASH} ${SRC_SMARTCARD} ${SRC_FPC} + ${SRC_BWM} ${SRC_HITAG} ${SRC_EM4x50} ${SRC_EM4x70} diff --git a/armsrc/Makefile b/armsrc/Makefile index 7778cd88d..9faca1ab4 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -119,7 +119,7 @@ else endif ifneq (,$(findstring WITH_BWM_FORWARD,$(APP_CFLAGS))) - SRC_BWM = bwm_uart_at32.c bwm_forward.c bwm_wifi.c + SRC_BWM = bwm_uart_at32.c bwm_forward.c bwm_wifi.c bwm_frame.c else SRC_BWM = endif diff --git a/armsrc/bwm_forward.c b/armsrc/bwm_forward.c index b92132159..2470cd281 100644 --- a/armsrc/bwm_forward.c +++ b/armsrc/bwm_forward.c @@ -14,7 +14,6 @@ #include "bwm_forward.h" #include "bwm_uart_at32.h" -#include "bwm_wifi.h" // BWM_CMD_CMD_ERROR #include "pm3_cmd.h" // PM3_CMD_DATA_SIZE, PM3_* return codes #include "ticks_apis.h" // SpinDelay #include "string.h" @@ -23,22 +22,6 @@ #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif -// CRC-16/CCITT-FALSE, byte-identical to the BWM firmware's crc16_ccitt() -// (poly 0x1021, init 0xFFFF, MSB-first, no reflection, no xorout). -static uint16_t bwm_crc16(const uint8_t *data, size_t len, uint16_t crc) { - for (size_t i = 0; i < len; i++) { - crc ^= (uint16_t)data[i] << 8; - for (uint8_t b = 0; b < 8; b++) { - if (crc & 0x8000) { - crc = (uint16_t)((crc << 1) ^ BWM_CRC16_POLY); - } else { - crc = (uint16_t)(crc << 1); - } - } - } - return crc; -} - // --------------------------------------------------------------------------- // TX: wrap one reply frame into a SEND_FORWARD_DATA app_com frame. // A full NG/OLD frame is <= PM3_CMD_DATA_SIZE + a small header/postamble, well @@ -96,14 +79,6 @@ void bwm_fwd_fc_stats(bwm_fc_stats_t *out) { out->in_flight_bytes = s_fc_bytes; } -// Set true by the parser when a SLAVE_RESP echoing BWM_CMD_SET_UART_BAUD arrives -// (the ESP's ack for a baud-set request). Consumed by bwm_fwd_negotiate_baud(). -static volatile bool s_baud_ack = false; - -// Set true by the parser on a SLAVE_RESP for BWM_CMD_GET_UART_BAUD - proof the -// ESP is alive and responding at the baud we just switched to (verify step). -static volatile bool s_getbaud_ack = false; - // Last LINK_STATE broadcast from the ESP: a client on BLE / on the TCP server. static volatile uint8_t s_link_ble = 0; static volatile uint8_t s_link_wifi = 0; @@ -116,6 +91,21 @@ void bwm_fwd_link_seed_ble(bool connected) { s_link_ble = connected ? 1 : 0; } +void bwm_fwd_on_frame_ack(void) { + s_fc_stats.acks++; + fc_pop(); +} + +void bwm_fwd_on_frame_error(void) { + s_fc_stats.errors++; + fc_pop(); +} + +void bwm_fwd_on_link_state(uint8_t ble, uint8_t wifi) { + s_link_ble = ble; + s_link_wifi = wifi; +} + int bwm_fwd_writebuffer_sync(const uint8_t *data, size_t len) { static uint8_t frame[BWM_TX_BUFSZ]; // single-threaded bare-metal: static OK @@ -123,7 +113,6 @@ int bwm_fwd_writebuffer_sync(const uint8_t *data, size_t len) { len = BWM_TX_MAX_PAYLOAD; // defensive; should never trigger } - size_t idx = 0; // Flow control: block while this frame would not fit the in-flight byte budget // (or the length FIFO is full). bwm_pump() drains the IRQ-filled RX ring, so // acks land even inside a tight download loop (the reply_old firehose). The @@ -146,188 +135,16 @@ int bwm_fwd_writebuffer_sync(const uint8_t *data, size_t len) { } } - frame[idx++] = BWM_HDR_HOST_CMD_1; - frame[idx++] = BWM_HDR_HOST_CMD_2; - frame[idx++] = (uint8_t)(BWM_CMD_SEND_FORWARD_DATA & 0xFF); - frame[idx++] = (uint8_t)((BWM_CMD_SEND_FORWARD_DATA >> 8) & 0xFF); - frame[idx++] = (uint8_t)(len & 0xFF); - frame[idx++] = (uint8_t)((len >> 8) & 0xFF); - if (len) { - memcpy(&frame[idx], data, len); - idx += len; + size_t n = bwm_frame_build(BWM_CMD_SEND_FORWARD_DATA, data, (uint16_t)len, + frame, sizeof(frame)); + if (n == 0) { + return PM3_EOVFLOW; } - uint16_t crc = bwm_crc16(frame, idx, BWM_CRC16_INIT); - frame[idx++] = (uint8_t)(crc & 0xFF); - frame[idx++] = (uint8_t)((crc >> 8) & 0xFF); - - int wr = bwm_uart_write(frame, idx); - fc_push((uint16_t)idx); // one more forward frame awaiting its ack + int wr = bwm_uart_write(frame, n); + fc_push((uint16_t)n); // one more forward frame awaiting its ack return wr; } -// --------------------------------------------------------------------------- -// RX: persistent app_com de-framer. Feeds raw FPC bytes through a state machine -// and pushes the payloads of valid DATA_FORWARD (0xD2 0xD3 / cmd 8089) frames -// into a byte FIFO that bwm_read_ng() drains. Non-DATA_FORWARD frames (slave -// responses, forwarded logs, cmd-error reports) are validated and discarded. -// --------------------------------------------------------------------------- -#define BWM_DEFIFO_SZ 2048 // >= one full NG frame's payload -#define BWM_RXFRAME_MAX (PM3_CMD_DATA_SIZE + 64) - -typedef enum { - S_IDLE = 0, S_HDR2, S_CMD_LO, S_CMD_HI, S_LEN_LO, S_LEN_HI, S_PAYLOAD, S_CRC_LO, S_CRC_HI -} bwm_state_t; - -typedef struct { - bwm_state_t state; - uint8_t hdr1; - bool is_bcast; // header pair is 0xD2 0xD3 - uint16_t cmd; - uint16_t len; - uint16_t got; // payload bytes received - uint16_t crc_calc; // running CRC over hdr..payload - uint16_t crc_recv; - uint8_t payload[BWM_RXFRAME_MAX]; -} bwm_parser_t; - -static bwm_parser_t s_p = { .state = S_IDLE }; - -// De-framed payload ring -static uint8_t s_fifo[BWM_DEFIFO_SZ]; -static volatile uint16_t s_fifo_head = 0; // write -static volatile uint16_t s_fifo_tail = 0; // read - -static uint16_t fifo_count(void) { - return (uint16_t)((s_fifo_head - s_fifo_tail) & (BWM_DEFIFO_SZ - 1)); -} -static void fifo_push(uint8_t b) { - uint16_t next = (uint16_t)((s_fifo_head + 1) & (BWM_DEFIFO_SZ - 1)); - if (next != s_fifo_tail) { // drop on overflow rather than corrupt - s_fifo[s_fifo_head] = b; - s_fifo_head = next; - } -} -static uint8_t fifo_pop(void) { - uint8_t b = s_fifo[s_fifo_tail]; - s_fifo_tail = (uint16_t)((s_fifo_tail + 1) & (BWM_DEFIFO_SZ - 1)); - return b; -} - -static void bwm_reset_frame(bwm_parser_t *p) { - p->state = S_IDLE; -} - -// Update running CRC one byte at a time (mirrors the streaming update in the -// BWM firmware parser). -static void crc_step(bwm_parser_t *p, uint8_t byte) { - p->crc_calc = bwm_crc16(&byte, 1, p->crc_calc); -} - -static void bwm_feed_byte(bwm_parser_t *p, uint8_t byte) { - switch (p->state) { - case S_IDLE: - if (byte == BWM_HDR_SLAVE_BCAST_1) { - p->hdr1 = byte; - p->is_bcast = true; - p->state = S_HDR2; - } else if (byte == BWM_HDR_SLAVE_RESP_1) { - p->hdr1 = byte; - p->is_bcast = false; - p->state = S_HDR2; - } - // any other byte: stay idle (resync) - break; - - case S_HDR2: { - bool ok = (p->is_bcast && byte == BWM_HDR_SLAVE_BCAST_2) || - (!p->is_bcast && byte == BWM_HDR_SLAVE_RESP_2); - if (!ok) { - // header mismatch: reset and re-examine this byte as a potential SOF - p->state = S_IDLE; - bwm_feed_byte(p, byte); - return; - } - uint8_t hdr[2] = { p->hdr1, byte }; - p->crc_calc = bwm_crc16(hdr, 2, BWM_CRC16_INIT); - p->state = S_CMD_LO; - break; - } - - case S_CMD_LO: - p->cmd = byte; - crc_step(p, byte); - p->state = S_CMD_HI; - break; - case S_CMD_HI: - p->cmd |= (uint16_t)byte << 8; - crc_step(p, byte); - p->state = S_LEN_LO; - break; - case S_LEN_LO: - p->len = byte; - crc_step(p, byte); - p->state = S_LEN_HI; - break; - case S_LEN_HI: - p->len |= (uint16_t)byte << 8; - crc_step(p, byte); - p->got = 0; - if (p->len > BWM_RXFRAME_MAX) { // oversized -> drop frame - bwm_reset_frame(p); - } else { - p->state = (p->len == 0) ? S_CRC_LO : S_PAYLOAD; - } - break; - - case S_PAYLOAD: - p->payload[p->got++] = byte; - crc_step(p, byte); - if (p->got >= p->len) { - p->state = S_CRC_LO; - } - break; - - case S_CRC_LO: - p->crc_recv = byte; - p->state = S_CRC_HI; - break; - case S_CRC_HI: - p->crc_recv |= (uint16_t)byte << 8; - if (p->crc_recv == p->crc_calc) { - if (p->is_bcast && p->cmd == BWM_CMD_DATA_FORWARD) { - for (uint16_t i = 0; i < p->len; i++) { - fifo_push(p->payload[i]); - } - } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SEND_FORWARD_DATA) { - // SLAVE_RESP ack for a forward frame -> its bytes leave the budget - s_fc_stats.acks++; - fc_pop(); - } else if (p->is_bcast && p->cmd == BWM_CMD_CMD_ERROR && p->len >= 2 && - (((uint16_t)p->payload[0] | ((uint16_t)p->payload[1] << 8)) == BWM_CMD_SEND_FORWARD_DATA)) { - // the ESP could not deliver a forward frame: this is its answer instead of the ack - s_fc_stats.errors++; - fc_pop(); - } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SET_UART_BAUD) { - // SLAVE_RESP ack for a baud-set request (see negotiate below) - s_baud_ack = true; - } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_GET_UART_BAUD) { - // SLAVE_RESP for our GET_BAUD verify probe - s_getbaud_ack = true; - } else if (p->is_bcast && p->cmd == BWM_CMD_LINK_STATE && p->len >= 2) { - s_link_ble = p->payload[0]; - s_link_wifi = p->payload[1]; - } - } - // valid non-DATA_FORWARD frames and CRC failures alike: just resync - bwm_reset_frame(p); - break; - - default: - bwm_reset_frame(p); - break; - } -} - // Pull whatever raw framed bytes are waiting and run them through the parser. static void bwm_pump(void) { uint8_t scratch[64]; @@ -338,20 +155,20 @@ static void bwm_pump(void) { break; } for (uint32_t i = 0; i < n; i++) { - bwm_feed_byte(&s_p, scratch[i]); + bwm_frame_feed(scratch[i]); } avail = bwm_uart_rx_available(); } } uint16_t bwm_fwd_rxdata_available(void) { - if (fifo_count() > 0) { - return fifo_count(); + if (bwm_fifo_count() > 0) { + return bwm_fifo_count(); } // No de-framed payload yet, but raw frame bytes may be waiting; pump once so // receive_ng()'s gate reflects real forward data. bwm_pump(); - return fifo_count(); + return bwm_fifo_count(); } uint32_t bwm_read_ng(uint8_t *data, size_t len) { @@ -370,16 +187,16 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len) { uint32_t out = 0; uint32_t try = 0; while (out < len) { - while (out < len && fifo_count() > 0) { - data[out++] = fifo_pop(); + while (out < len && bwm_fifo_count() > 0) { + data[out++] = bwm_fifo_pop(); try = 0; } if (out >= len) { break; } - uint16_t before = fifo_count(); + uint16_t before = bwm_fifo_count(); bwm_pump(); - if (fifo_count() != before) { + if (bwm_fifo_count() != before) { try = 0; continue; } @@ -390,7 +207,6 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len) { return out; } - // --------------------------------------------------------------------------- // Runtime baud negotiation. // The ESP boots at BWM_UART_BAUD and accepts a HOST_CMD (cmd 1011) carrying a @@ -413,26 +229,15 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len) { // i.e. it really is running at the baud we just switched to. Retried by the // caller so a single lost probe on a good link does not force a needless revert. static bool bwm_verify_baud(void) { - uint8_t f[2 + 2 + 2 + 2]; - size_t i = 0; - f[i++] = BWM_HDR_HOST_CMD_1; - f[i++] = BWM_HDR_HOST_CMD_2; - f[i++] = (uint8_t)(BWM_CMD_GET_UART_BAUD & 0xFF); - f[i++] = (uint8_t)((BWM_CMD_GET_UART_BAUD >> 8) & 0xFF); - f[i++] = 0; - f[i++] = 0; - uint16_t crc = bwm_crc16(f, i, BWM_CRC16_INIT); - f[i++] = (uint8_t)(crc & 0xFF); - f[i++] = (uint8_t)((crc >> 8) & 0xFF); - - s_getbaud_ack = false; - s_p.state = S_IDLE; - bwm_uart_write(f, i); + uint8_t f[8]; + size_t n = bwm_frame_build(BWM_CMD_GET_UART_BAUD, NULL, 0, f, sizeof(f)); + bwm_frame_clear_getbaud_ack(); + bwm_uart_write(f, n); uint32_t t0 = GetTickCount(); while (GetTickCountDelta(t0) < BWM_BAUD_VERIFY_MS) { bwm_pump(); - if (s_getbaud_ack) { + if (bwm_frame_getbaud_ack()) { return true; } } @@ -453,9 +258,7 @@ static bool bwm_probe_at(uint32_t baud, int tries) { // Reset framer, FIFO and flow control after a baud change. static void bwm_link_reset(void) { - s_p.state = S_IDLE; - s_fifo_head = 0; - s_fifo_tail = 0; + bwm_frame_reset(); fc_reset(); } @@ -485,30 +288,21 @@ bool bwm_fwd_negotiate_baud(uint32_t target) { } // Build the SET_UART_BAUD host-command frame once (payload = u32 LE baud). - uint8_t frame[2 + 2 + 2 + 4 + 2]; - size_t idx = 0; - frame[idx++] = BWM_HDR_HOST_CMD_1; - frame[idx++] = BWM_HDR_HOST_CMD_2; - frame[idx++] = (uint8_t)(BWM_CMD_SET_UART_BAUD & 0xFF); - frame[idx++] = (uint8_t)((BWM_CMD_SET_UART_BAUD >> 8) & 0xFF); - frame[idx++] = (uint8_t)(4 & 0xFF); - frame[idx++] = (uint8_t)((4 >> 8) & 0xFF); - frame[idx++] = (uint8_t)(target & 0xFF); - frame[idx++] = (uint8_t)((target >> 8) & 0xFF); - frame[idx++] = (uint8_t)((target >> 16) & 0xFF); - frame[idx++] = (uint8_t)((target >> 24) & 0xFF); - uint16_t crc = bwm_crc16(frame, idx, BWM_CRC16_INIT); - frame[idx++] = (uint8_t)(crc & 0xFF); - frame[idx++] = (uint8_t)((crc >> 8) & 0xFF); + uint8_t payload[4]; + payload[0] = (uint8_t)(target & 0xFF); + payload[1] = (uint8_t)((target >> 8) & 0xFF); + payload[2] = (uint8_t)((target >> 16) & 0xFF); + payload[3] = (uint8_t)((target >> 24) & 0xFF); + uint8_t frame[12]; + size_t idx = bwm_frame_build(BWM_CMD_SET_UART_BAUD, payload, 4, frame, sizeof(frame)); for (int attempt = 0; attempt < BWM_BAUD_ATTEMPTS; attempt++) { - s_baud_ack = false; - s_p.state = S_IDLE; // drop any half-frame before we listen + bwm_frame_clear_baud_ack(); bwm_uart_write(frame, idx); for (int ms = 0; ms < BWM_BAUD_ACK_WAIT_MS; ms++) { bwm_pump(); // parser sets s_baud_ack on the SLAVE_RESP - if (s_baud_ack) { + if (bwm_frame_baud_ack()) { // ESP acked and is switching; verify it before trusting the // new baud, else fall back so both ends stay in sync. bool verified = bwm_probe_at(target, BWM_BAUD_VERIFY_TRIES); diff --git a/armsrc/bwm_forward.h b/armsrc/bwm_forward.h index 6d9e01c03..ba562e56a 100644 --- a/armsrc/bwm_forward.h +++ b/armsrc/bwm_forward.h @@ -10,20 +10,6 @@ //----------------------------------------------------------------------------- // Proxmark5 Battery Wireless Module (BWM) transport shim. // -// The BWM (ESP32-C2, RfidResearchGroup/Proxmark5_BWM_esp32) bridges the AT32 -// host <-> BLE/WiFi. Its ESP<->AT32 UART link does NOT carry raw PacketCommandNG; -// it uses a framed "app_com" protocol. Transparent host<->wireless traffic rides -// inside that framing: -// -// AT32 -> ESP (our reply, toward wireless host): -// [0x7C 0xC7] cmd=APP_CMD_SEND_FORWARD_DATA(5000) len(LE) payload CRC16(LE) -// ESP -> AT32 (command from wireless host): -// [0xD2 0xD3] cmd=APP_BROADCAST_DATA_FORWARD(8089) len(LE) payload CRC16(LE) -// -// Frame = HDR1 HDR2 | CMD(LE16) | LEN(LE16) | PAYLOAD[LEN] | CRC(LE16) -// CRC = CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, MSB-first, no xorout) -// over HDR..PAYLOAD. (NOT compute_crc(CRC_14443_A) - different CRC.) -// // This shim wraps outgoing NG/OLD reply bytes into a SEND_FORWARD_DATA frame and // de-frames incoming DATA_FORWARD frames back into a raw NG byte stream, so the // stock reply_ng()/receive_ng() paths work unchanged over the BWM link. @@ -35,24 +21,8 @@ #define __BWM_FORWARD_H #include "common.h" +#include "bwm_frame.h" -// app_com framing constants (verified against BWM firmware app_cmd_uart.[ch] / -// app_com_defs.h). -#define BWM_HDR_HOST_CMD_1 0x7C // AT32 -> ESP (host command) -#define BWM_HDR_HOST_CMD_2 0xC7 -#define BWM_HDR_SLAVE_BCAST_1 0xD2 // ESP -> AT32 (slave broadcast) -#define BWM_HDR_SLAVE_BCAST_2 0xD3 -#define BWM_HDR_SLAVE_RESP_1 0x2D // ESP -> AT32 (slave response; forward-frame ack) -#define BWM_HDR_SLAVE_RESP_2 0x3D - -#define BWM_CMD_SEND_FORWARD_DATA 5000 // host cmd: payload -> BLE/WiFi endpoint -#define BWM_CMD_DATA_FORWARD 8089 // slave bcast: payload came from endpoint -#define BWM_CMD_LINK_STATE 8092 // slave bcast: [ble u8][wifi u8], 1 = a client is connected -// System command: set the ESP<->AT32 UART baud (app_com_defs.h, enum @1000). -// SET is a HOST_CMD carrying u32 LE baud; the ESP replies with a SLAVE_RESP -// echoing this cmd (len 0) at the OLD baud, then commits to the new baud. -#define BWM_CMD_SET_UART_BAUD 1011 -#define BWM_CMD_GET_UART_BAUD 1009 // read back the ESP's live baud (negotiation verify) // Flow control (byte window). The ESP acks each forward frame with a SLAVE_RESP // echoing SEND_FORWARD_DATA once it has taken the frame out of its UART ring // (module firmware from the companion PR; older firmware acks after the radio, @@ -78,9 +48,6 @@ #define BWM_FC_ACK_TIMEOUT_MS 200 // safety valve: proceed if acks stall, never hard-hang #endif // safety valve: give up waiting for credit (avoid hard hang) -#define BWM_CRC16_POLY 0x1021 -#define BWM_CRC16_INIT 0xFFFF - // Wrap `len` raw reply bytes (a whole PacketResponseNG/OLD frame) into one // SEND_FORWARD_DATA app_com frame and write it synchronously to the FPC USART. // Returns PM3_SUCCESS or the underlying usart error. Drop-in for the FPC diff --git a/armsrc/bwm_wifi.h b/armsrc/bwm_wifi.h index 3a58b605c..23b34211d 100644 --- a/armsrc/bwm_wifi.h +++ b/armsrc/bwm_wifi.h @@ -35,7 +35,9 @@ #define BWM_CMD_SET_TCP_SERVER_PORT 2205 // payload: uint16 LE port #define BWM_WIFI_FORWARD_TCP_SERVER 0 // wifi_forward_type_t::WIFI_FORWARD_TCP_SERVER +#ifndef BWM_CMD_CMD_ERROR #define BWM_CMD_CMD_ERROR 8091 // slave bcast: command error report +#endif #define BWM_CMD_LOG_FORWARD_ENABLE 1014 // payload: u8 (0=stop, non-zero=start) #define BWM_CMD_LOG_MESSAGE 8090 // slave bcast: ESP_LOGx output (string) diff --git a/bootrom/CMakeLists.txt b/bootrom/CMakeLists.txt index b4d50bb09..662028380 100644 --- a/bootrom/CMakeLists.txt +++ b/bootrom/CMakeLists.txt @@ -21,6 +21,7 @@ set(DEFAULT_VERSION_C ${CMAKE_CURRENT_LIST_DIR}/../common/default_version_pm3.c) set(VERSION_PM3_C ${CMAKE_CURRENT_BINARY_DIR}/version_pm3.c) set(INC_DIRS + ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_CURRENT_LIST_DIR}/../include ${CMAKE_CURRENT_LIST_DIR}/../common ${CMAKE_CURRENT_LIST_DIR}/../common_arm/sys @@ -29,6 +30,7 @@ set(INC_DIRS ${CMAKE_CURRENT_LIST_DIR}/../common_arm/gpio ${CMAKE_CURRENT_LIST_DIR}/../common_arm/usb ${CMAKE_CURRENT_LIST_DIR}/../common_arm/ticks + ${CMAKE_CURRENT_LIST_DIR}/../common_arm/bwm ) set(THUMBSRC @@ -45,6 +47,10 @@ if (PM5) ${CMAKE_CURRENT_LIST_DIR}/../common_arm/flash_code/flash_code_hw_at32.c ) set(ASMSRC flash-reset-at32.s ram-reset-at32.s) + if ("${PLATFORM_DEFS}" MATCHES "WITH_BWM_FORWARD") + set(THUMBSRC ${THUMBSRC} ${CMAKE_CURRENT_LIST_DIR}/bwm_boot.c + ${CMAKE_CURRENT_LIST_DIR}/../common_arm/bwm/bwm_frame.c) + endif () else () set(THUMBSRC ${THUMBSRC} ${CMAKE_CURRENT_LIST_DIR}/../common_arm/sys/sys_hw_at91.c diff --git a/bootrom/Makefile b/bootrom/Makefile index 519e14800..0ebe1312a 100644 --- a/bootrom/Makefile +++ b/bootrom/Makefile @@ -17,6 +17,18 @@ # Makefile for bootrom, see ../common_arm/Makefile.common for common settings #----------------------------------------------------------------------------- +# This Makefile might have been called directly, not via the root Makefile, so: +ifeq ($(PLTNAME),) + PLATFORM_FILE ?= ../Makefile.platform + -include $(PLATFORM_FILE) + -include ../.Makefile.options.cache + -include ../armsrc/Standalone/Makefile.hal + include ../common_arm/Makefile.hal + ifeq ($(PLATFORM_CHANGED), true) + $(error platform definitions have been changed, please "make clean" at the root of the project) + endif +endif + # Proxmark5 requires armlib. include ../armlib/Exports.mk @@ -48,6 +60,9 @@ endif # DO NOT use thumb mode in the phase 1 bootloader since that generates a section with glue code ARMSRC = THUMBSRC = bootrom.c $(SRC_SYS) $(SRC_TICKS) $(SRC_GPIO) $(SRC_USB_CDC) $(SRC_FLASH_CODE) usb_cdc_desc.c +ifneq (,$(findstring WITH_BWM_FORWARD,$(PLATFORM_DEFS))) + THUMBSRC += bwm_boot.c bwm_frame.c +endif ASMSRC = $(SRC_STARTUP) VERSIONSRC = version_pm3.c @@ -67,11 +82,22 @@ APP_CFLAGS += -fno-common APP_CFLAGS += $(ARMLIB_EXPORT_CFLAGS) ifneq (,$(findstring WITH_FLASH,$(PLATFORM_DEFS))) - APP_CFLAGS += -DWITH_FLASH - APP_CFLAGS += -I../common_arm + APP_CFLAGS += -DWITH_FLASH + APP_CFLAGS += -I../common_arm THUMBSRC += ticks_core.c flashmem_core.c $(SRC_FLASH_DATA) endif +ifneq (,$(findstring WITH_BWM_FORWARD,$(PLATFORM_DEFS))) + APP_CFLAGS += -DWITH_BWM_FORWARD +endif + +# PLATFORM_EXTRAS=BWM is a no-op unless Makefile.hal filled PLATFORM_DEFS. +ifneq (,$(findstring BWM,$(PLATFORM_EXTRAS))) +ifeq (,$(findstring WITH_BWM_FORWARD,$(PLATFORM_DEFS))) + $(error PLATFORM_EXTRAS=BWM did not set WITH_BWM_FORWARD. Build bootrom from the repo root (`make bootrom`) or let this Makefile include common_arm/Makefile.hal.) +endif +endif + # Do not move this inclusion before the definition of {THUMB,ASM,ARM}SRC include ../common_arm/Makefile.common diff --git a/bootrom/bootrom.c b/bootrom/bootrom.c index fd1af10bc..814df4f7b 100644 --- a/bootrom/bootrom.c +++ b/bootrom/bootrom.c @@ -28,6 +28,9 @@ #ifdef WITH_FLASH #include "flashmem.h" #endif +#ifdef WITH_BWM_FORWARD +#include "bwm_boot.h" +#endif #define DEBUG 0 // At present, in the case of at32 with a flash size of 4m byte, a sector is 4096 bytes. @@ -52,6 +55,11 @@ flash_min_unit_data_t flash_min_unit_data; extern uint32_t _bootrom_start[], _bootrom_end[], _flash_start[], _flash_end[], __bss_start__[], __bss_end__[]; extern uint32_t _osimage_entry[], _stack_start[], _stack_end[]; +#ifdef WITH_BWM_FORWARD +static bool g_pkt_from_bwm; +static uint32_t s_fw_addr; +#endif + // Send an old frame response packet. static int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) { PacketResponseOLD txcmd; @@ -73,6 +81,11 @@ static int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, } } +#ifdef WITH_BWM_FORWARD + if (g_pkt_from_bwm) { + return bwm_boot_write((uint8_t *)&txcmd, sizeof(PacketResponseOLD)); + } +#endif // Send frame and make sure all bytes are transmitted return usb_write((uint8_t *)&txcmd, sizeof(PacketResponseOLD)); } @@ -99,9 +112,11 @@ static void DbpString(char *str) { } #endif +#ifndef WITH_BWM_FORWARD static void Fatal(void) { for (;;) {}; } +#endif static void UsbPacketReceived(uint8_t *packet) { bool ack = true; @@ -122,12 +137,19 @@ static void UsbPacketReceived(uint8_t *packet) { DEVICE_INFO_FLAG_UNDERSTANDS_VERSION | DEVICE_INFO_FLAG_UNDERSTANDS_READ_MEM | DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE; +#ifdef WITH_BWM_FORWARD + arg0 |= DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM; +#endif if (g_common_area.flags.osimage_present) { arg0 |= DEVICE_INFO_FLAG_OSIMAGE_PRESENT; } +#ifdef WITH_BWM_FORWARD + reply_old(CMD_DEVICE_INFO, arg0, 1, bwm_boot_baud(), 0, 0); +#else reply_old(CMD_DEVICE_INFO, arg0, 1, 2, 0, 0); +#endif } break; @@ -240,13 +262,40 @@ static void UsbPacketReceived(uint8_t *packet) { // than one erase/write unit (e.g. AT91 pages of 256 bytes), so always copy it in and flush // the whole units below instead of assuming the payload is no larger than one unit. bool copy_overflow = false; - for (int i = 0; i < usb_payload_u32_len; i++) { - // Check data buffer is no overflow. - if (flash_min_unit_data.count >= ARRAYLEN(flash_min_unit_data.data)) { - copy_overflow = true; +#ifdef WITH_BWM_FORWARD + if (g_pkt_from_bwm) { + // arg[2] is the byte offset in the unit. Place, don't append. + uint32_t off = (uint32_t)c->arg[2]; + uint32_t idx = off / sizeof(uint32_t); + if ((off % sizeof(c->d)) || + ((idx + usb_payload_u32_len) > ARRAYLEN(flash_min_unit_data.data))) { + ack = false; + flash_min_unit_data.count = 0; + reply_old(CMD_NACK, 0, PM3_EINVARG, 0, 0, 0); break; } - flash_min_unit_data.data[flash_min_unit_data.count++] = c->d.asDwords[i]; + if (flash_min_unit_data.count && (s_fw_addr != arg0)) { + flash_min_unit_data.count = 0; + } + s_fw_addr = arg0; + for (int i = 0; i < usb_payload_u32_len; i++) { + flash_min_unit_data.data[idx + i] = c->d.asDwords[i]; + } + uint32_t end = idx + usb_payload_u32_len; + if (end > flash_min_unit_data.count) { + flash_min_unit_data.count = end; + } + } else +#endif + { + for (int i = 0; i < usb_payload_u32_len; i++) { + // Check data buffer is no overflow. + if (flash_min_unit_data.count >= ARRAYLEN(flash_min_unit_data.data)) { + copy_overflow = true; + break; + } + flash_min_unit_data.data[flash_min_unit_data.count++] = c->d.asDwords[i]; + } } if (copy_overflow) { ack = false; @@ -269,6 +318,9 @@ static void UsbPacketReceived(uint8_t *packet) { // Call the cross-platform flash api to write firmware to flash. uint32_t status = 0x00; bool isok = FlashCodeEWriteMinUnit(flash_address, flash_min_unit_addr, _flash_start, &status); +#ifdef WITH_BWM_FORWARD + bwm_boot_pump(); +#endif if (!isok) { ack = false; reply_old(CMD_NACK, status, 0, 0, 0, 0); @@ -320,7 +372,11 @@ static void UsbPacketReceived(uint8_t *packet) { break; default: { +#ifdef WITH_BWM_FORWARD + ack = false; +#else Fatal(); +#endif } break; } @@ -355,22 +411,50 @@ static void flash_mode(void) { // wait for reset to be complete? SpinDelayUs(300 * 1000); // Wait for 300ms +#ifdef WITH_BWM_FORWARD + bwm_boot_init(); +#endif + for (;;) { WDT_HIT(); +#ifdef WITH_BWM_FORWARD + // Before the USB poll, not only after it: UART4 holds a single byte. + bwm_boot_pump(); +#endif + // Check if there is a usb packet available if (usb_poll_validate_length()) { if (usb_read(rx, sizeof(rx))) { +#ifdef WITH_BWM_FORWARD + g_pkt_from_bwm = false; +#endif UsbPacketReceived(rx); } } +#ifdef WITH_BWM_FORWARD + while (bwm_boot_poll(rx, sizeof(rx))) { + g_pkt_from_bwm = true; + UsbPacketReceived(rx); + } +#endif + bool button_state = BUTTON_PRESS(); +#ifdef WITH_BWM_FORWARD + // UART4 holds one byte and has no DMA. A 10 ms sleep on every loop + // would shred an inbound DATA_FORWARD, so only debounce on a press. + if (button_state) { + SpinDelayUs(10000); + button_state = BUTTON_PRESS(); + } +#else SpinDelayUs(10000); // ~10ms, prevent jitter if (button_state != BUTTON_PRESS()) { // in jitter state, ignore continue; } +#endif if (g_common_area.flags.button_pressed && button_state == false) { g_common_area.flags.button_pressed = 0; } diff --git a/bootrom/bwm_boot.c b/bootrom/bwm_boot.c new file mode 100644 index 000000000..25f60ccf5 --- /dev/null +++ b/bootrom/bwm_boot.c @@ -0,0 +1,259 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Polled UART4 + app_com unwrap. No DMA, no RX FIFO: one byte in the receive +// register. Pump within one byte time (~10.8 us at 921600) or it is lost. +//----------------------------------------------------------------------------- + +#ifndef WITH_BWM_FORWARD +#error "bwm_boot.c requires WITH_BWM_FORWARD" +#endif + +#include "bwm_boot.h" + +#include "bwm_frame.h" +#include "commonutil.h" +#include "pm3_cmd.h" +#include "ticks_apis.h" +#include "at32f435_437.h" +#include "at32f435_437_crm.h" +#include "at32f435_437_gpio.h" +#include "at32f435_437_usart.h" + +extern uint32_t start_addr, end_addr; + +#define BWM_UART UART4 +#define BWM_UART_GPIO GPIOA +#define BWM_UART_TX_PIN GPIO_PINS_0 +#define BWM_UART_RX_PIN GPIO_PINS_1 +#define BWM_UART_TX_SRC GPIO_PINS_SOURCE0 +#define BWM_UART_RX_SRC GPIO_PINS_SOURCE1 +#define BWM_UART_MUX GPIO_MUX_8 + +// ESP UART baud is not persistent. Probe both; 921600 is the OS target. +static const uint32_t s_baud_candidates[] = { 921600u, 460800u }; + +#define BWM_PROBE_ROUNDS 3 + +// SpinDelayUs() uses SysTick. Do not bound these waits with GetTicks()/TMR5: +// that timer is otherwise unused here, and a dead counter would hang without +// WDT_HIT(). 1 us stays inside one byte time. +#define BWM_SPIN_US 1u +#define BWM_PROBE_WAIT_US 30000u +#define BWM_ACK_WAIT_US 50000u + +// Idle flush only: StartTicks() runs TMR5 at 1.5 MHz. If it never advances, +// the delta stays 0 and the flush does not fire. +#define BWM_TICKS_PER_MS 1500u +#define BWM_STAGE_IDLE_MS 1000u + +static uint8_t s_cmd[sizeof(PacketCommandOLD)]; +static uint16_t s_got; +static uint32_t s_stage_tick; +static uint32_t s_baud; + +static bool bwm_old_cmd_ok(const uint8_t *p) { + const PacketCommandOLD *c = (const PacketCommandOLD *)p; + uint32_t cmd = (uint32_t)c->cmd; + uint32_t a0 = (uint32_t)c->arg[0]; + if (c->cmd != cmd) { + return false; + } + switch (cmd) { + case CMD_DEVICE_INFO: + case CMD_HARDWARE_RESET: + case CMD_START_FLASH: + case CMD_CHIP_INFO: + case CMD_BL_VERSION: + case CMD_CHIP_TYPE: + case CMD_READ_MEM_DOWNLOAD: + return true; + case CMD_FINISH_WRITE: + return (start_addr != end_addr) && + (a0 >= start_addr) && + (a0 < end_addr); + default: + return false; + } +} + +static void uart_set_baud(uint32_t baud) { + crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE); + crm_periph_clock_enable(CRM_UART4_PERIPH_CLOCK, TRUE); + + gpio_init_type gpio_init_struct; + gpio_default_para_init(&gpio_init_struct); + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_pull = GPIO_PULL_NONE; + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_pins = BWM_UART_TX_PIN | BWM_UART_RX_PIN; + gpio_init(BWM_UART_GPIO, &gpio_init_struct); + gpio_pin_mux_config(BWM_UART_GPIO, BWM_UART_TX_SRC, BWM_UART_MUX); + gpio_pin_mux_config(BWM_UART_GPIO, BWM_UART_RX_SRC, BWM_UART_MUX); + + usart_enable(BWM_UART, FALSE); + usart_init(BWM_UART, baud, USART_DATA_8BITS, USART_STOP_1_BIT); + usart_parity_selection_config(BWM_UART, USART_PARITY_NONE); + usart_transmitter_enable(BWM_UART, TRUE); + usart_receiver_enable(BWM_UART, TRUE); + usart_enable(BWM_UART, TRUE); +} + +static int uart_getc(uint8_t *b) { + if (usart_flag_get(BWM_UART, USART_ROERR_FLAG) != RESET) { + (void)usart_data_receive(BWM_UART); + usart_flag_clear(BWM_UART, USART_ROERR_FLAG); + return 0; + } + if (usart_flag_get(BWM_UART, USART_RDBF_FLAG) == RESET) { + return 0; + } + *b = (uint8_t)usart_data_receive(BWM_UART); + return 1; +} + +void bwm_boot_pump(void) { + uint8_t b; + while (uart_getc(&b)) { + bwm_frame_feed(b); + } +} + +// Pump while waiting for TX: a 552 B frame is ~6 ms of deafness otherwise. +static void uart_write(const uint8_t *d, size_t n) { + for (size_t i = 0; i < n; i++) { + while (usart_flag_get(BWM_UART, USART_TDBE_FLAG) == RESET) { + bwm_boot_pump(); + } + usart_data_transmit(BWM_UART, d[i]); + } + while (usart_flag_get(BWM_UART, USART_TDC_FLAG) == RESET) { + bwm_boot_pump(); + } +} + +static void uart_drain(void) { + uint8_t dump; + while (uart_getc(&dump)) {} +} + +static bool bwm_probe_once(void) { + uint8_t f[8]; + size_t n = bwm_frame_build(BWM_CMD_GET_UART_BAUD, NULL, 0, f, sizeof(f)); + if (n == 0) { + return false; + } + bwm_frame_reset(); + uart_write(f, n); + for (uint32_t us = 0; us < BWM_PROBE_WAIT_US; us += BWM_SPIN_US) { + bwm_boot_pump(); + if (bwm_frame_getbaud_ack()) { + bwm_frame_clear_getbaud_ack(); + return true; + } + SpinDelayUs(BWM_SPIN_US); + } + return false; +} + +void bwm_boot_init(void) { + StartTicks(); + s_got = 0; + s_stage_tick = GetTicks(); + s_baud = 0; + for (uint8_t round = 0; round < BWM_PROBE_ROUNDS; round++) { + for (uint8_t i = 0; i < ARRAYLEN(s_baud_candidates); i++) { + uart_set_baud(s_baud_candidates[i]); + uart_drain(); + if (bwm_probe_once()) { + s_baud = s_baud_candidates[i]; + bwm_frame_reset(); + return; + } + } + } + uart_set_baud(s_baud_candidates[0]); + uart_drain(); + bwm_frame_reset(); +} + +uint32_t bwm_boot_baud(void) { + return s_baud; +} + +bool bwm_boot_poll(uint8_t *out, size_t outlen) { + if (out == NULL || outlen < sizeof(s_cmd)) { + return false; + } + bwm_boot_pump(); + uint16_t slides = 0; + for (;;) { + uint16_t before = s_got; + while (s_got < sizeof(s_cmd) && bwm_fifo_count() > 0) { + s_cmd[s_got++] = bwm_fifo_pop(); + } + if (s_got != before) { + s_stage_tick = GetTicks(); + } + if (s_got < sizeof(s_cmd)) { + // Zero padding of an OLD frame looks like CMD_DEVICE_INFO. Drop a + // stalled partial rather than lock onto a bogus offset. + if (s_got && ((GetTicks() - s_stage_tick) > (BWM_STAGE_IDLE_MS * BWM_TICKS_PER_MS))) { + s_got = 0; + } + return false; + } + if (bwm_old_cmd_ok(s_cmd)) { + for (size_t i = 0; i < sizeof(s_cmd); i++) { + out[i] = s_cmd[i]; + } + s_got = 0; + return true; + } + for (size_t i = 0; i < sizeof(s_cmd) - 1; i++) { + s_cmd[i] = s_cmd[i + 1]; + } + s_got = sizeof(s_cmd) - 1; + bwm_boot_pump(); + if (++slides >= sizeof(s_cmd)) { + return false; + } + } +} + +int bwm_boot_write(const uint8_t *data, size_t len) { + if (data == NULL || len == 0 || len > 0xFFFF) { + return PM3_EINVARG; + } + uint8_t frame[8 + sizeof(PacketResponseOLD)]; + size_t n = bwm_frame_build(BWM_CMD_SEND_FORWARD_DATA, data, (uint16_t)len, + frame, sizeof(frame)); + if (n == 0) { + return PM3_EOVFLOW; + } + (void)bwm_frame_take_fwd_ack(); + uart_write(frame, n); + bwm_frame_inflight_inc(); + for (uint32_t us = 0; us < BWM_ACK_WAIT_US; us += BWM_SPIN_US) { + bwm_boot_pump(); + if (bwm_frame_take_fwd_ack()) { + return PM3_SUCCESS; + } + SpinDelayUs(BWM_SPIN_US); + } + bwm_frame_inflight_zero(); + return PM3_ETIMEOUT; +} diff --git a/bootrom/bwm_boot.h b/bootrom/bwm_boot.h new file mode 100644 index 000000000..736dd83be --- /dev/null +++ b/bootrom/bwm_boot.h @@ -0,0 +1,31 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// PM5 bootrom BWM UART: DATA_FORWARD is a byte stream of PacketCommandOLD. +//----------------------------------------------------------------------------- +#ifndef BWM_BOOT_H +#define BWM_BOOT_H + +#include "common.h" + +void bwm_boot_init(void); +void bwm_boot_pump(void); +bool bwm_boot_poll(uint8_t *out, size_t outlen); +int bwm_boot_write(const uint8_t *data, size_t len); + +// Baud the ESP answered on, or 0 if none did. +uint32_t bwm_boot_baud(void); + +#endif diff --git a/client/include/pm3.h b/client/include/pm3.h index 92e99bacd..fb60b391e 100644 --- a/client/include/pm3.h +++ b/client/include/pm3.h @@ -26,4 +26,6 @@ const char *pm3_grabbed_output_get(pm3 *dev); const char *pm3_name_get(pm3 *dev); void pm3_close(pm3 *dev); pm3 *pm3_get_current_dev(void); +int pm3_flash(const char *port, const char *const *images, int nimages, + bool unlock_bootloader, bool force); #endif // LIBPM3_H diff --git a/client/src/flash.c b/client/src/flash.c index 5df376b9a..28169e5e8 100644 --- a/client/src/flash.c +++ b/client/src/flash.c @@ -462,11 +462,34 @@ fail: return res; } +static bool port_is_wireless(const char *name) { + if (name == NULL) { + return false; + } + return (strncmp(name, "tcp:", 4) == 0) || + (strncmp(name, "udp:", 4) == 0) || + (strncmp(name, "bt:", 3) == 0); +} + // Get the state of the proxmark, backwards compatible -static int get_proxmark_state(uint32_t *state) { - SendCommandBL(CMD_DEVICE_INFO, 0, 0, 0, NULL, 0); +static int get_proxmark_state(uint32_t *state, const char *serial_port_name) { PacketResponseNG resp; - WaitForResponse(CMD_UNKNOWN, &resp); // wait for any response. No timeout. + bool got = false; + for (int attempt = 0; (attempt < 3) && (got == false); attempt++) { + clearCommandBuffer(); + SendCommandBL(CMD_DEVICE_INFO, 0, 0, 0, NULL, 0); + got = WaitForResponseTimeout(CMD_UNKNOWN, &resp, 3000); + } + if (got == false) { + if (port_is_wireless(serial_port_name)) { + PrintAndLogEx(ERR, "No reply from bootloader. Wireless bootrom is not talking BWM."); + PrintAndLogEx(INFO, "Flash a BWM-capable bootrom over USB: " _YELLOW_("make clean && make bootrom") " then ./pm3-flash-bootrom"); + } else { + PrintAndLogEx(ERR, "No reply from bootloader."); + } + PrintAndLogEx(INFO, "Nothing was written. Short-press the button to leave flash mode."); + return PM3_ETIMEOUT; + } // Three outcomes: // 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK @@ -485,6 +508,15 @@ static int get_proxmark_state(uint32_t *state) { case CMD_DEVICE_INFO: { // bootloader replies are OLD frames by design, see doc/new_frame_format.md *state = resp.oldarg[0]; + PrintAndLogEx(DEBUG, "DEVICE_INFO flags 0x%08x", *state); + // A BWM bootrom reports the baud it probed in oldarg[2]; 0 means no ESP answered. + if ((*state & DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM) == DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM) { + if (resp.oldarg[2]) { + PrintAndLogEx(INFO, "Bootloader BWM link at " _YELLOW_("%" PRIu64) " baud", resp.oldarg[2]); + } else { + PrintAndLogEx(WARNING, "Bootloader found no BWM module (no ESP answered on 921600 or 460800)"); + } + } break; } default: { @@ -499,7 +531,7 @@ static int get_proxmark_state(uint32_t *state) { static int enter_bootloader(char *serial_port_name, bool wait_appear) { uint32_t state = 0; - int ret = get_proxmark_state(&state); + int ret = get_proxmark_state(&state, serial_port_name); if (ret != PM3_SUCCESS) { return ret; } @@ -547,15 +579,31 @@ static int enter_bootloader(char *serial_port_name, bool wait_appear) { // Wait for the device to respond with either ACK or NACK. static int wait_for_ack(PacketResponseNG *ack) { - WaitForResponse(CMD_UNKNOWN, ack); - if (ack->cmd != CMD_ACK) { + // Timeout + skip stale replies (a lost byte can yield cmd 0x0000). + uint64_t deadline = msclock() + 15000; + for (;;) { + uint64_t now = msclock(); + if (now >= deadline) { + PrintAndLogEx(ERR, "No ACK from bootloader (timeout)"); + return PM3_ETIMEOUT; + } + if (WaitForResponseTimeout(CMD_UNKNOWN, ack, deadline - now) == false) { + PrintAndLogEx(ERR, "No ACK from bootloader (timeout)"); + return PM3_ETIMEOUT; + } + if (ack->cmd == CMD_ACK) { + return PM3_SUCCESS; + } + if (ack->cmd != CMD_NACK) { + PrintAndLogEx(DEBUG, "Discarding stale reply 0x%04x while waiting for ACK", ack->cmd); + continue; + } PrintAndLogEx(ERR, "\nError: Unexpected reply 0x%04x %s (expected ACK)", ack->cmd, (ack->cmd == CMD_NACK) ? "NACK" : "" ); return PM3_ESOFT; } - return PM3_SUCCESS; } // If the BOOTLOADER is too old or damaged, we can suggest that the user update the BOOT. @@ -664,10 +712,15 @@ static bool files_target_bootloader(flash_file_t *files, uint8_t num_files, uint // Sending simple cmd without any parameters or data payload, just for arg0. static void send_cmd_for_arg0(const uint64_t cmd, uint32_t *arg0) { - SendCommandBL(cmd, 0, 0, 0, NULL, 0); - PacketResponseNG resp; - WaitForResponse(cmd, &resp); - *arg0 = resp.oldarg[0]; + for (int attempt = 0; attempt < 2; attempt++) { + clearCommandBuffer(); + SendCommandBL(cmd, 0, 0, 0, NULL, 0); + PacketResponseNG resp; + if (WaitForResponseTimeout(cmd, &resp, 8000)) { + *arg0 = resp.oldarg[0]; + return; + } + } } // Go into flashing mode @@ -679,11 +732,19 @@ int flash_start_flashing(int enable_bl_writes, char *serial_port_name, flash_dev } uint32_t state = 0; - ret = get_proxmark_state(&state); + ret = get_proxmark_state(&state, serial_port_name); if (ret != PM3_SUCCESS) { return ret; } + if (port_is_wireless(serial_port_name) && + ((state & DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM) != DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM)) { + PrintAndLogEx(ERR, "This bootloader cannot flash over a wireless link (flags 0x%08x)", state); + PrintAndLogEx(INFO, "Flash the bootrom over USB once, then retry."); + PrintAndLogEx(INFO, "Nothing was written. Short-press the button to leave flash mode."); + return PM3_EOPABORTED; + } + flash_dev->chiptype = MAIN_CHIP_TYPE_NONE; if ((state & DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE) == DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE) { send_cmd_for_arg0(CMD_CHIP_TYPE, &flash_dev->chiptype); @@ -834,13 +895,15 @@ static void flash_write_err_software(int pm3_err) { // Send finish write cmd and waiting for response. // The send_buf length is always 512byte(PM3_CMD_DATA_SIZE_OLD) -static int send_finish_write_cmd(uint32_t address, int magic, uint8_t *send_buf, PacketResponseNG *resp) { +// block_off is the byte offset within the erase/write unit (unused on ICOPYX). +static int send_finish_write_cmd(uint32_t address, int magic, uint32_t block_off, uint8_t *send_buf, PacketResponseNG *resp) { // The sending length is always PM3_CMD_DATA_SIZE_OLD, which is 512 bytes, because of the limitation of the old frame. const int send_len = PM3_CMD_DATA_SIZE_OLD; #if defined ICOPYX // To prevent users from flashing unsupported firmware, icopyx checks arg1 and arg2 in this command. // Therefore, when sending magic to the device, we should not choose a value that happens to be the same as icopyx. // In fact, neither PM3V nor PM5V will be 0xff or 0x1fd, so this should have strong robustness. + (void)block_off; SendCommandBL(CMD_FINISH_WRITE, address, 0xff, 0x1fd, send_buf, send_len); #else // If it's an older version of the flasher or a flasher specific to icopyx, then arg1 should be 0x00 or 0xff, @@ -859,7 +922,8 @@ static int send_finish_write_cmd(uint32_t address, int magic, uint8_t *send_buf, // --- // The new client version can always continue to OTA update the device version, // and can also OTA update the latest version of PM5. - SendCommandBL(CMD_FINISH_WRITE, address, magic, 0, send_buf, send_len); + // arg[2] is the byte offset within the unit. Old bootroms ignore it; BWM bootroms place at arg[2]/4. + SendCommandBL(CMD_FINISH_WRITE, address, magic, block_off, send_buf, send_len); #endif return wait_for_ack(resp); } @@ -884,27 +948,40 @@ static int write_block(uint32_t address, int magic, uint8_t *data, uint32_t leng memcpy(block_buf, data, length); // copy data by valid length // Send in packets int ret = PM3_SUCCESS; - uint32_t sent = 0; - while (sent < aligned_len) { - PacketResponseNG resp; - ret = send_finish_write_cmd(address, magic, block_buf + sent, &resp); - if (ret) { - // On new version of flasher, the arg1 is error code of PM3_E*, old version is 0x00, so we can always check it. - if (resp.oldarg[1]) { // 0x00 == PM3_SUCCESS - flash_write_err_software(resp.oldarg[1]); - } else { - // If not PM3_E*, maybe some errors of flash write occurred. Or is old version boot. - if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT91) { - flash_write_err_on_at91(resp.oldarg[0]); - } else if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT32) { - flash_write_err_on_at32(resp.oldarg[0]); - } else { - PrintAndLogEx(ERR, "Unknown chip type, cannot decode error information"); + for (int attempt = 0; attempt < 4; attempt++) { + uint32_t sent = 0; + ret = PM3_SUCCESS; + while (sent < aligned_len) { + PacketResponseNG resp; + ret = send_finish_write_cmd(address, magic, sent, block_buf + sent, &resp); + if (ret) { + if (ret == PM3_ETIMEOUT) { + PrintAndLogEx(WARNING, "No ACK at 0x%08x (packet %u), retrying block", + address, sent / PM3_CMD_DATA_SIZE_OLD); + msleep(400); + break; } + // On new version of flasher, the arg1 is error code of PM3_E*, old version is 0x00, so we can always check it. + if (resp.oldarg[1]) { // 0x00 == PM3_SUCCESS + flash_write_err_software(resp.oldarg[1]); + } else { + // If not PM3_E*, maybe some errors of flash write occurred. Or is old version boot. + if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT91) { + flash_write_err_on_at91(resp.oldarg[0]); + } else if (flash_dev->chiptype == MAIN_CHIP_TYPE_AT32) { + flash_write_err_on_at32(resp.oldarg[0]); + } else { + PrintAndLogEx(ERR, "Unknown chip type, cannot decode error information"); + } + } + free(block_buf); // remember to free buffer + return ret; } + sent += PM3_CMD_DATA_SIZE_OLD; + } + if (ret == PM3_SUCCESS && sent >= aligned_len) { break; } - sent += PM3_CMD_DATA_SIZE_OLD; } free(block_buf); // remember to free buffer return ret; diff --git a/client/src/pm3.c b/client/src/pm3.c index 1c4088305..76df67ac2 100644 --- a/client/src/pm3.c +++ b/client/src/pm3.c @@ -27,6 +27,7 @@ #include "util_posix.h" #include "comms.h" #include "preferences.h" +#include "flash.h" pm3_device_t *pm3_open(const char *port) { pm3_init(); @@ -92,3 +93,24 @@ const char *pm3_grabbed_output_get(pm3_device_t *dev) { pm3_device_t *pm3_get_current_dev(void) { return g_session.current_device; } + +int pm3_flash(const char *port, const char *const *images, int nimages, + bool unlock_bootloader, bool force) { + if ((port == NULL) || (images == NULL) || (nimages < 1) || (nimages > FLASH_MAX_FILES)) { + return PM3_EINVARG; + } + + const char *files[FLASH_MAX_FILES] = {0}; + for (int i = 0; i < nimages; ++i) { + if (images[i] == NULL) { + return PM3_EINVARG; + } + files[i] = images[i]; + } + + // Don't send CMD_QUIT_SESSION — we're about to reset into bootrom. + if (g_session.pm3_present) { + CloseProxmark(g_session.current_device); + } + return flash_pm3((char *)port, (uint8_t)nimages, files, unlock_bootloader, force); +} diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index bc9a3b0d8..5fb731d0d 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -982,7 +982,9 @@ finish: return ret; } -static int flash_pm3(char *serial_port_name, uint8_t num_files, const char *filenames[FLASH_MAX_FILES], bool can_write_bl, bool force) { +#endif //LIBPM3 + +int flash_pm3(char *serial_port_name, uint8_t num_files, const char *filenames[], bool can_write_bl, bool force) { int ret = PM3_EUNDEF; flash_file_t files[FLASH_MAX_FILES] = {0}; @@ -994,14 +996,19 @@ static int flash_pm3(char *serial_port_name, uint8_t num_files, const char *file } for (int i = 0 ; i < num_files; ++i) { - char *path; - ret = searchFile(&path, FIRMWARES_SUBDIR, filenames[i], ".elf", true); - if (ret != PM3_SUCCESS) { - ret = searchFile(&path, BOOTROM_SUBDIR, filenames[i], ".elf", true); - } - if (ret != PM3_SUCCESS) { - // Last try, let the error msg be displayed if not found - ret = searchFile(&path, FULLIMAGE_SUBDIR, filenames[i], ".elf", false); + char *path = NULL; + // Don't let searchFile append ".elf" onto an already-copied path. + if (path_is_regular_file(filenames[i])) { + path = str_dup(filenames[i]); + ret = (path == NULL) ? PM3_EMALLOC : PM3_SUCCESS; + } else { + ret = searchFile(&path, FIRMWARES_SUBDIR, filenames[i], ".elf", true); + if (ret != PM3_SUCCESS) { + ret = searchFile(&path, BOOTROM_SUBDIR, filenames[i], ".elf", true); + } + if (ret != PM3_SUCCESS) { + ret = searchFile(&path, FULLIMAGE_SUBDIR, filenames[i], ".elf", false); + } } if (ret != PM3_SUCCESS) { goto finish2; @@ -1083,6 +1090,7 @@ finish2: return ret; } +#ifndef LIBPM3 static int reboot_bootloader_pm3(char *serial_port_name) { if (serial_port_name == NULL) { PrintAndLogEx(ERR, "You must specify a port.\n"); diff --git a/client/src/proxmark3.h b/client/src/proxmark3.h index 25c7c8059..85ad35da9 100644 --- a/client/src/proxmark3.h +++ b/client/src/proxmark3.h @@ -60,6 +60,7 @@ extern "C" { #endif int push_cmdscriptfile(char *path, bool stayafter); +int flash_pm3(char *serial_port_name, uint8_t num_files, const char *filenames[], bool can_write_bl, bool force); const char *get_my_executable_path(void); const char *get_my_executable_directory(void); const char *get_my_user_directory(void); diff --git a/common_arm/Hal.cmake b/common_arm/Hal.cmake index 6cde005c0..7f2faa907 100644 --- a/common_arm/Hal.cmake +++ b/common_arm/Hal.cmake @@ -20,9 +20,11 @@ set_property(CACHE PLATFORM PROPERTY STRINGS "PM3RDV4" "PM3GENERIC" "PM3ICOPYX" +============================================+ | BTADDON | Proxmark3 RDV4 BT add-on | +--------------------------------------------+ +| BWM | PM5 Battery Wireless Mod | ++--------------------------------------------+ ]] set(PLATFORM_EXTRAS "" CACHE STRING "Default PLATFORM_EXTRAS is unset") -set_property(CACHE PLATFORM_EXTRAS PROPERTY STRINGS "BTADDON" "") +set_property(CACHE PLATFORM_EXTRAS PROPERTY STRINGS "BTADDON" "BWM" "") # Skip fpga bit stream files pack to arm's fw? # Some platform is no download in arm side required. @@ -110,6 +112,13 @@ if ("${PLATFORM_EXTRAS_TMP}" MATCHES "BTADDON") list(APPEND PLATFORM_DEFS -DWITH_FPC_USART_HOST) list(REMOVE_ITEM PLATFORM_EXTRAS_TMP "BTADDON") endif () +if ("${PLATFORM_EXTRAS_TMP}" MATCHES "BWM") + if (NOT PLATFORM STREQUAL "PM5") + message(FATAL_ERROR "PLATFORM_EXTRAS token BWM is only valid on PLATFORM=PM5") + endif () + list(APPEND PLATFORM_DEFS -DWITH_BWM_FORWARD) + list(REMOVE_ITEM PLATFORM_EXTRAS_TMP "BWM") +endif () if ("${PLATFORM_EXTRAS_TMP}" MATCHES "FPC_USART_DEV") list(APPEND PLATFORM_DEFS -DWITH_FPC_USART_DEV) list(REMOVE_ITEM PLATFORM_EXTRAS_TMP "FPC_USART_DEV") diff --git a/common_arm/Makefile.common b/common_arm/Makefile.common index 174313200..a1e76887a 100644 --- a/common_arm/Makefile.common +++ b/common_arm/Makefile.common @@ -44,11 +44,13 @@ OBJDIR = obj INCLUDE = -I../include -I../common_arm -I../common_fpga -I../common -I. INCLUDE += -I../common_arm/flash_code -I../common_arm/flash_data -I../common_arm/fpga -I../common_arm/gpio INCLUDE += -I../common_arm/rssi -I../common_arm/rgb -I../common_arm/sys -I../common_arm/ticks -I../common_arm/usb -I../common_arm/wdt +INCLUDE += -I../common_arm/bwm # Also search prerequisites in the common directory (for usb.c), the fpga directory (for fpga.bit), and the lz4 directory VPATH = . ../common_arm ../common ../common/crapto1 ../common/mbedtls ../common/lz4 ../fpga ../armsrc/Standalone ../common/hitag2 VPATH += ../common_arm/flash_code ../common_arm/flash_data ../common_arm/fpga ../common_arm/gpio VPATH += ../common_arm/rssi ../common_arm/rgb ../common_arm/sys ../common_arm/ticks ../common_arm/usb ../common_arm/wdt +VPATH += ../common_arm/bwm INCLUDES = ../include/proxmark3_arm.h ../include/at91sam7s512.h ../include/config_gpio.h ../include/pm3_cmd.h diff --git a/common_arm/bwm/bwm_frame.c b/common_arm/bwm/bwm_frame.c new file mode 100644 index 000000000..5e578ecb8 --- /dev/null +++ b/common_arm/bwm/bwm_frame.c @@ -0,0 +1,301 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// BWM app_com de-framer. See bwm_frame.h. +//----------------------------------------------------------------------------- + +#include "bwm_frame.h" + +// CRC-16/CCITT-FALSE, byte-identical to the BWM firmware's crc16_ccitt() +// (poly 0x1021, init 0xFFFF, MSB-first, no reflection, no xorout). +uint16_t bwm_crc16(const uint8_t *data, size_t len, uint16_t crc) { + for (size_t i = 0; i < len; i++) { + crc ^= (uint16_t)data[i] << 8; + for (uint8_t b = 0; b < 8; b++) { + if (crc & 0x8000) { + crc = (uint16_t)((crc << 1) ^ BWM_CRC16_POLY); + } else { + crc = (uint16_t)(crc << 1); + } + } + } + return crc; +} + +// --------------------------------------------------------------------------- +// RX: persistent app_com de-framer. Feeds raw FPC bytes through a state machine +// and pushes the payloads of valid DATA_FORWARD (0xD2 0xD3 / cmd 8089) frames +// into a byte FIFO that bwm_read_ng() drains. Non-DATA_FORWARD frames (slave +// responses, forwarded logs, cmd-error reports) are validated and discarded. +// --------------------------------------------------------------------------- +typedef enum { + S_IDLE = 0, S_HDR2, S_CMD_LO, S_CMD_HI, S_LEN_LO, S_LEN_HI, S_PAYLOAD, S_CRC_LO, S_CRC_HI +} bwm_state_t; + +typedef struct { + bwm_state_t state; + uint8_t hdr1; + bool is_bcast; // header pair is 0xD2 0xD3 + uint16_t cmd; + uint16_t len; + uint16_t got; // payload bytes received + uint16_t crc_calc; // running CRC over hdr..payload + uint16_t crc_recv; + uint8_t payload[BWM_FRAME_RX_MAX]; +} bwm_parser_t; + +static bwm_parser_t s_p = { .state = S_IDLE }; + +// De-framed payload ring +static uint8_t s_fifo[BWM_FIFO_SZ]; +static volatile uint16_t s_fifo_head = 0; // write +static volatile uint16_t s_fifo_tail = 0; // read + +// --- Flow control (ack window) --------------------------------------------- +// s_fwd_inflight: forward frames sent but not yet acked by the ESP. Bumped on +// send, decremented when a SLAVE_RESP echoing cmd=SEND_FORWARD_DATA arrives. +// We may send while it is below BWM_FC_WINDOW; at the cap we wait for an ack. +static volatile int16_t s_fwd_inflight = 0; +// Bootrom write path waits for this; OS only uses the inflight count. +static volatile bool s_fwd_ack = false; + +// Set true by the parser when a SLAVE_RESP echoing BWM_CMD_SET_UART_BAUD arrives +// (the ESP's ack for a baud-set request). Consumed by bwm_fwd_negotiate_baud(). +static volatile bool s_baud_ack = false; + +// Set true by the parser on a SLAVE_RESP for BWM_CMD_GET_UART_BAUD - proof the +// ESP is alive and responding at the baud we just switched to (verify step). +static volatile bool s_getbaud_ack = false; + +static uint16_t fifo_count(void) { + return (uint16_t)((s_fifo_head - s_fifo_tail) & (BWM_FIFO_SZ - 1)); +} +static void fifo_push(uint8_t b) { + uint16_t next = (uint16_t)((s_fifo_head + 1) & (BWM_FIFO_SZ - 1)); + if (next != s_fifo_tail) { // drop on overflow rather than corrupt + s_fifo[s_fifo_head] = b; + s_fifo_head = next; + } +} +static uint8_t fifo_pop(void) { + uint8_t b = s_fifo[s_fifo_tail]; + s_fifo_tail = (uint16_t)((s_fifo_tail + 1) & (BWM_FIFO_SZ - 1)); + return b; +} + +static void bwm_reset_frame(bwm_parser_t *p) { + p->state = S_IDLE; +} + +// Update running CRC one byte at a time (mirrors the streaming update in the +// BWM firmware parser). +static void crc_step(bwm_parser_t *p, uint8_t byte) { + p->crc_calc = bwm_crc16(&byte, 1, p->crc_calc); +} + +static void bwm_feed_byte(bwm_parser_t *p, uint8_t byte) { + switch (p->state) { + case S_IDLE: + if (byte == BWM_HDR_SLAVE_BCAST_1) { + p->hdr1 = byte; + p->is_bcast = true; + p->state = S_HDR2; + } else if (byte == BWM_HDR_SLAVE_RESP_1) { + p->hdr1 = byte; + p->is_bcast = false; + p->state = S_HDR2; + } + // any other byte: stay idle (resync) + break; + + case S_HDR2: { + bool ok = (p->is_bcast && byte == BWM_HDR_SLAVE_BCAST_2) || + (!p->is_bcast && byte == BWM_HDR_SLAVE_RESP_2); + if (!ok) { + // header mismatch: reset and re-examine this byte as a potential SOF + p->state = S_IDLE; + bwm_feed_byte(p, byte); + return; + } + uint8_t hdr[2] = { p->hdr1, byte }; + p->crc_calc = bwm_crc16(hdr, 2, BWM_CRC16_INIT); + p->state = S_CMD_LO; + break; + } + + case S_CMD_LO: + p->cmd = byte; + crc_step(p, byte); + p->state = S_CMD_HI; + break; + case S_CMD_HI: + p->cmd |= (uint16_t)byte << 8; + crc_step(p, byte); + p->state = S_LEN_LO; + break; + case S_LEN_LO: + p->len = byte; + crc_step(p, byte); + p->state = S_LEN_HI; + break; + case S_LEN_HI: + p->len |= (uint16_t)byte << 8; + crc_step(p, byte); + p->got = 0; + if (p->len > BWM_FRAME_RX_MAX) { // oversized -> drop frame + bwm_reset_frame(p); + } else { + p->state = (p->len == 0) ? S_CRC_LO : S_PAYLOAD; + } + break; + + case S_PAYLOAD: + p->payload[p->got++] = byte; + crc_step(p, byte); + if (p->got >= p->len) { + p->state = S_CRC_LO; + } + break; + + case S_CRC_LO: + p->crc_recv = byte; + p->state = S_CRC_HI; + break; + case S_CRC_HI: + p->crc_recv |= (uint16_t)byte << 8; + if (p->crc_recv == p->crc_calc) { + if (p->is_bcast && p->cmd == BWM_CMD_DATA_FORWARD) { + for (uint16_t i = 0; i < p->len; i++) { + fifo_push(p->payload[i]); + } + } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SEND_FORWARD_DATA) { + // SLAVE_RESP ack for a forward frame -> one slot freed + if (s_fwd_inflight > 0) { + s_fwd_inflight--; + } + s_fwd_ack = true; +#ifndef AS_BOOTROM + bwm_fwd_on_frame_ack(); +#endif + } else if (p->is_bcast && p->cmd == BWM_CMD_CMD_ERROR && p->len >= 2 && + (((uint16_t)p->payload[0] | ((uint16_t)p->payload[1] << 8)) == BWM_CMD_SEND_FORWARD_DATA)) { + // the ESP could not deliver a forward frame: this is its answer instead of the ack +#ifndef AS_BOOTROM + bwm_fwd_on_frame_error(); +#endif + } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_SET_UART_BAUD) { + // SLAVE_RESP ack for a baud-set request (see negotiate below) + s_baud_ack = true; + } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_GET_UART_BAUD) { + // SLAVE_RESP for our GET_BAUD verify probe + s_getbaud_ack = true; + } else if (p->is_bcast && p->cmd == BWM_CMD_LINK_STATE && p->len >= 2) { +#ifndef AS_BOOTROM + bwm_fwd_on_link_state(p->payload[0], p->payload[1]); +#endif + } + } + // valid non-DATA_FORWARD frames and CRC failures alike: just resync + bwm_reset_frame(p); + break; + + default: + bwm_reset_frame(p); + break; + } +} + +void bwm_frame_feed(uint8_t byte) { + bwm_feed_byte(&s_p, byte); +} + +uint16_t bwm_fifo_count(void) { + return fifo_count(); +} + +uint8_t bwm_fifo_pop(void) { + return fifo_pop(); +} + +int16_t bwm_frame_inflight(void) { + return s_fwd_inflight; +} + +void bwm_frame_inflight_inc(void) { + s_fwd_inflight++; +} + +void bwm_frame_inflight_zero(void) { + s_fwd_inflight = 0; +} + +bool bwm_frame_take_fwd_ack(void) { + if (s_fwd_ack == false) { + return false; + } + s_fwd_ack = false; + return true; +} + +bool bwm_frame_baud_ack(void) { + return s_baud_ack; +} + +void bwm_frame_clear_baud_ack(void) { + s_baud_ack = false; + s_p.state = S_IDLE; // drop any half-frame before we listen +} + +bool bwm_frame_getbaud_ack(void) { + return s_getbaud_ack; +} + +void bwm_frame_clear_getbaud_ack(void) { + s_getbaud_ack = false; + s_p.state = S_IDLE; +} + +void bwm_frame_reset(void) { + s_p.state = S_IDLE; + s_fifo_head = 0; + s_fifo_tail = 0; + s_fwd_inflight = 0; + s_fwd_ack = false; + s_baud_ack = false; + s_getbaud_ack = false; +} + +size_t bwm_frame_build(uint16_t cmd, const uint8_t *payload, uint16_t len, + uint8_t *out, size_t outsz) { + size_t idx = 0; + if (out == NULL || outsz < (size_t)(8 + len)) { + return 0; + } + out[idx++] = BWM_HDR_HOST_CMD_1; + out[idx++] = BWM_HDR_HOST_CMD_2; + out[idx++] = (uint8_t)(cmd & 0xFF); + out[idx++] = (uint8_t)((cmd >> 8) & 0xFF); + out[idx++] = (uint8_t)(len & 0xFF); + out[idx++] = (uint8_t)((len >> 8) & 0xFF); + if (len && payload) { + for (uint16_t i = 0; i < len; i++) { + out[idx++] = payload[i]; + } + } + uint16_t crc = bwm_crc16(out, idx, BWM_CRC16_INIT); + out[idx++] = (uint8_t)(crc & 0xFF); + out[idx++] = (uint8_t)((crc >> 8) & 0xFF); + return idx; +} diff --git a/common_arm/bwm/bwm_frame.h b/common_arm/bwm/bwm_frame.h new file mode 100644 index 000000000..a21cbb434 --- /dev/null +++ b/common_arm/bwm/bwm_frame.h @@ -0,0 +1,103 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// BWM app_com de-framer shared by the PM5 OS and bootrom. +// +// The BWM (ESP32-C2, RfidResearchGroup/Proxmark5_BWM_esp32) bridges the AT32 +// host <-> BLE/WiFi. Its ESP<->AT32 UART link does NOT carry raw PacketCommandNG; +// it uses a framed "app_com" protocol. Transparent host<->wireless traffic rides +// inside that framing: +// +// AT32 -> ESP (our reply, toward wireless host): +// [0x7C 0xC7] cmd=APP_CMD_SEND_FORWARD_DATA(5000) len(LE) payload CRC16(LE) +// ESP -> AT32 (command from wireless host): +// [0xD2 0xD3] cmd=APP_BROADCAST_DATA_FORWARD(8089) len(LE) payload CRC16(LE) +// +// Frame = HDR1 HDR2 | CMD(LE16) | LEN(LE16) | PAYLOAD[LEN] | CRC(LE16) +// CRC = CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, MSB-first, no xorout) +// over HDR..PAYLOAD. (NOT compute_crc(CRC_14443_A) - different CRC.) +//----------------------------------------------------------------------------- +#ifndef BWM_FRAME_H +#define BWM_FRAME_H + +#include "common.h" +#include "pm3_cmd.h" + +// app_com framing constants (verified against BWM firmware app_cmd_uart.[ch] / +// app_com_defs.h). +#define BWM_HDR_HOST_CMD_1 0x7C // AT32 -> ESP (host command) +#define BWM_HDR_HOST_CMD_2 0xC7 +#define BWM_HDR_SLAVE_BCAST_1 0xD2 // ESP -> AT32 (slave broadcast) +#define BWM_HDR_SLAVE_BCAST_2 0xD3 +#define BWM_HDR_SLAVE_RESP_1 0x2D // ESP -> AT32 (slave response; forward-frame ack) +#define BWM_HDR_SLAVE_RESP_2 0x3D + +#define BWM_CMD_SEND_FORWARD_DATA 5000 // host cmd: payload -> BLE/WiFi endpoint +#define BWM_CMD_DATA_FORWARD 8089 // slave bcast: payload came from endpoint +#define BWM_CMD_CMD_ERROR 8091 // slave bcast: command error report +#define BWM_CMD_LINK_STATE 8092 // slave bcast: [ble u8][wifi u8], 1 = a client is connected +// System command: set the ESP<->AT32 UART baud (app_com_defs.h, enum @1000). +// SET is a HOST_CMD carrying u32 LE baud; the ESP replies with a SLAVE_RESP +// echoing this cmd (len 0) at the OLD baud, then commits to the new baud. +#define BWM_CMD_SET_UART_BAUD 1011 +#define BWM_CMD_GET_UART_BAUD 1009 // read back the ESP's live baud (negotiation verify) + +#define BWM_CRC16_POLY 0x1021 +#define BWM_CRC16_INIT 0xFFFF + +#ifdef AS_BOOTROM +#ifndef BWM_FRAME_RX_MAX +#define BWM_FRAME_RX_MAX 576 +#endif +#ifndef BWM_FIFO_SZ +#define BWM_FIFO_SZ 1024 +#endif +#else +#ifndef BWM_FRAME_RX_MAX +#define BWM_FRAME_RX_MAX (PM3_CMD_DATA_SIZE + 64) // NG/OLD frame ceiling +#endif +#ifndef BWM_FIFO_SZ +#define BWM_FIFO_SZ 2048 // >= one full NG frame's payload +#endif +#endif + +uint16_t bwm_crc16(const uint8_t *data, size_t len, uint16_t crc); + +void bwm_frame_reset(void); +void bwm_frame_feed(uint8_t byte); + +uint16_t bwm_fifo_count(void); +uint8_t bwm_fifo_pop(void); + +int16_t bwm_frame_inflight(void); +void bwm_frame_inflight_inc(void); +void bwm_frame_inflight_zero(void); + +bool bwm_frame_take_fwd_ack(void); +bool bwm_frame_baud_ack(void); +void bwm_frame_clear_baud_ack(void); +bool bwm_frame_getbaud_ack(void); +void bwm_frame_clear_getbaud_ack(void); + +size_t bwm_frame_build(uint16_t cmd, const uint8_t *payload, uint16_t len, + uint8_t *out, size_t outsz); + +#ifndef AS_BOOTROM +void bwm_fwd_on_frame_ack(void); +void bwm_fwd_on_frame_error(void); +void bwm_fwd_on_link_state(uint8_t ble, uint8_t wifi); +#endif + +#endif diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 33f0564ce..6b21c5c4f 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -1550,6 +1550,9 @@ typedef struct { /* Set if this device understands the chip type command */ #define DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_TYPE (1<<8) +/* Bootrom de-frames BWM DATA_FORWARD as a byte stream (OLD cmds may span frames) */ +#define DEVICE_INFO_FLAG_UNDERSTANDS_BWM_STREAM (1 << 9) + #define BL_VERSION_MAJOR(version) ((uint32_t)(version) >> 22) #define BL_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff) #define BL_VERSION_PATCH(version) ((uint32_t)(version) & 0xfff)