Skip to content

Commit

Permalink
Add static asserts to validate circular buffer sizes
Browse files Browse the repository at this point in the history
Circular buffers using unmasked indices have size restrictions:
* The size must be an exact power of two
* The size cannot be greater than half of the max value represented
   by the index type
Buffers used to process data from USB out endpoints must also be big
enough to hold at least one maximum size packet to prevent the flow
control logic from NAK'ing all packets.
  • Loading branch information
devanlai committed May 21, 2017
1 parent 38961c6 commit 488dcdb
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/CAN/can.c
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@

#if CAN_RX_AVAILABLE

#define IS_POW_OF_TWO(X) (((X) & ((X)-1)) == 0)
_Static_assert(IS_POW_OF_TWO(CAN_RX_BUFFER_SIZE),
"Unmasked circular buffer size must be a power of two");
_Static_assert(CAN_RX_BUFFER_SIZE <= UINT8_MAX/2,
"Buffer size too big for unmasked circular buffer");

static volatile CAN_Message can_rx_buffer[CAN_RX_BUFFER_SIZE];
static volatile uint8_t can_rx_head = 0;
static volatile uint8_t can_rx_tail = 0;
Expand Down
3 changes: 3 additions & 0 deletions src/USB/cdc.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@

#if CDC_AVAILABLE

_Static_assert((CONSOLE_TX_BUFFER_SIZE >= USB_CDC_MAX_PACKET_SIZE),
"TX buffer too small");

/* Descriptors */
const struct cdc_acm_functional_descriptors cdc_acm_functional_descriptors = {
.header = {
Expand Down
13 changes: 13 additions & 0 deletions src/USB/vcdc.c
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ static uint16_t vcdc_tx_tail = 0;
static uint16_t vcdc_rx_head = 0;
static uint16_t vcdc_rx_tail = 0;

_Static_assert((VCDC_RX_BUFFER_SIZE >= USB_VCDC_MAX_PACKET_SIZE),
"RX buffer too small");

#define IS_POW_OF_TWO(X) (((X) & ((X)-1)) == 0)
_Static_assert(IS_POW_OF_TWO(VCDC_RX_BUFFER_SIZE),
"Unmasked circular buffer size must be a power of two");
_Static_assert(IS_POW_OF_TWO(VCDC_TX_BUFFER_SIZE),
"Unmasked circular buffer size must be a power of two");
_Static_assert(VCDC_TX_BUFFER_SIZE <= UINT16_MAX/2,
"Buffer size too big for unmasked circular buffer");
_Static_assert(VCDC_RX_BUFFER_SIZE <= UINT16_MAX/2,
"Buffer size too big for unmasked circular buffer");

static bool vcdc_tx_buffer_empty(void) {
return vcdc_tx_head == vcdc_tx_tail;
}
Expand Down

0 comments on commit 488dcdb

Please sign in to comment.