Skip to content

Commit

Permalink
Add magic keyword to detect memory corruption
Browse files Browse the repository at this point in the history
  • Loading branch information
MaJerle committed May 12, 2020
1 parent 47afec6 commit 05bc01f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions ringbuff/src/include/ringbuff/ringbuff.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ extern "C" {
*/
#define RINGBUFF_VOLATILE /* volatile */

/**
* \brief Adds 2 magic words to make sure if memory is corrupted
* application can detect wrong data pointer and maximum size
*/
#define RINGBUFF_USE_MAGIC 1

/**
* \brief Event type for buffer operations
*/
Expand All @@ -79,12 +85,18 @@ typedef void (*ringbuff_evt_fn)(RINGBUFF_VOLATILE struct ringbuff* buff, ringbuf
* \brief Buffer structure
*/
typedef struct ringbuff {
#ifdef RINGBUFF_USE_MAGIC
uint32_t magic1; /*!< Magic 1 word */
#endif /* RINGBUFF_USE_MAGIC */
uint8_t* buff; /*!< Pointer to buffer data.
Buffer is considered initialized when `buff != NULL` and `size > 0` */
size_t size; /*!< Size of buffer data. Size of actual buffer is `1` byte less than value holds */
size_t r; /*!< Next read pointer. Buffer is considered empty when `r == w` and full when `w == r - 1` */
size_t w; /*!< Next write pointer. Buffer is considered empty when `r == w` and full when `w == r - 1` */
ringbuff_evt_fn evt_fn; /*!< Pointer to event callback function */
#ifdef RINGBUFF_USE_MAGIC
uint32_t magic2; /*!< Magic 2 word */
#endif /* RINGBUFF_USE_MAGIC */
} ringbuff_t;

uint8_t ringbuff_init(RINGBUFF_VOLATILE ringbuff_t* buff, void* buffdata, size_t size);
Expand Down
10 changes: 10 additions & 0 deletions ringbuff/src/ringbuff/ringbuff.c
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@
/* Memory set and copy functions */
#define BUF_MEMSET memset
#define BUF_MEMCPY memcpy

#ifdef RINGBUFF_USE_MAGIC
#define BUF_IS_VALID(b) ((b) != NULL && (b)->magic1 == 0xDEADBEEF && (b)->magic2 == ~0xDEADBEEF && (b)->buff != NULL && (b)->size > 0)
#else
#define BUF_IS_VALID(b) ((b) != NULL && (b)->buff != NULL && (b)->size > 0)
#endif /* RINGBUFF_USE_MAGIC */
#define BUF_MIN(x, y) ((x) < (y) ? (x) : (y))
#define BUF_MAX(x, y) ((x) > (y) ? (x) : (y))
#define BUF_SEND_EVT(b, type, bp) do { if ((b)->evt_fn != NULL) { (b)->evt_fn((b), (type), (bp)); } } while (0)
Expand All @@ -60,6 +65,11 @@ ringbuff_init(RINGBUFF_VOLATILE ringbuff_t* buff, void* buffdata, size_t size) {
buff->size = size;
buff->buff = buffdata;

#ifdef RINGBUFF_USE_MAGIC
buff->magic1 = 0xDEADBEEF;
buff->magic2 = ~0xDEADBEEF;
#endif /* RINGBUFF_USE_MAGIC */

return 1;
}

Expand Down

0 comments on commit 05bc01f

Please sign in to comment.