From d75716054c59b7b0342064682f0f288fd989b58b Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 2 Jan 2025 22:13:08 -0800 Subject: [PATCH] Fix buffer underflow when receiving packets When using BTstack 1.6.2 (latest stable version), the microcontroller might crash due to buffer underflow. The byte before the first byte of hci_packet_with_pre_buffer will get overwritten. In particular the problem was that BTstack `setup_long_characteristic_value_packet()` was receiving `&hci_packet_with_pre_buffer[13]`, and in that function the packet gets overwritten starting from "- LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE", which is 14. So the byte before hci_packet_with_pre_buffer gets overwritten. See: https://github.com/bluekitchen/btstack/blob/5d4d8cc7b1d35a90bbd6d5ffd2d3050b2bfc861c/src/ble/gatt_client.c#L1060 This PR follows the same logic implemented in BTstack ESP32 port. See: https://github.com/bluekitchen/btstack/blob/develop/port/esp32/components/btstack/btstack_port_esp32.c#L104 Fixes https://github.com/bluekitchen/btstack/issues/651 --- .../pico_cyw43_driver/btstack_hci_transport_cyw43.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/rp2_common/pico_cyw43_driver/btstack_hci_transport_cyw43.c b/src/rp2_common/pico_cyw43_driver/btstack_hci_transport_cyw43.c index ecfcf3dbe..3c8d22461 100644 --- a/src/rp2_common/pico_cyw43_driver/btstack_hci_transport_cyw43.c +++ b/src/rp2_common/pico_cyw43_driver/btstack_hci_transport_cyw43.c @@ -34,6 +34,8 @@ static void (*hci_transport_cyw43_packet_handler)(uint8_t packet_type, uint8_t * // Incoming packet buffer - cyw43 packet header (incl packet type) + incoming pre buffer + max(acl header + acl payload, event header + event data) __attribute__((aligned(4))) static uint8_t hci_packet_with_pre_buffer[4 + HCI_INCOMING_PRE_BUFFER_SIZE + HCI_INCOMING_PACKET_BUFFER_SIZE ]; +static uint8_t * hci_receive_buffer = &hci_packet_with_pre_buffer[HCI_INCOMING_PRE_BUFFER_SIZE]; + static btstack_data_source_t transport_data_source; static bool hci_transport_ready; @@ -143,10 +145,10 @@ static void hci_transport_cyw43_process(void) { uint32_t loop_count = 0; #endif do { - int err = cyw43_bluetooth_hci_read(hci_packet_with_pre_buffer, sizeof(hci_packet_with_pre_buffer), &len); + int err = cyw43_bluetooth_hci_read(hci_receive_buffer, sizeof(hci_packet_with_pre_buffer) - HCI_INCOMING_PRE_BUFFER_SIZE, &len); BT_DEBUG("bt in len=%lu err=%d\n", len, err); if (err == 0 && len > 0) { - hci_transport_cyw43_packet_handler(hci_packet_with_pre_buffer[3], hci_packet_with_pre_buffer + 4, len - 4); + hci_transport_cyw43_packet_handler(hci_receive_buffer[3], &hci_receive_buffer[4], len - 4); has_work = true; } else { has_work = false;