Skip to content

Commit

Permalink
Fix buffer underflow when receiving packets
Browse files Browse the repository at this point in the history
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 bluekitchen/btstack#651
  • Loading branch information
ricardoquesada committed Jan 3, 2025
1 parent 969f589 commit d757160
Showing 1 changed file with 4 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit d757160

Please sign in to comment.