Skip to content

Commit

Permalink
store: don't underflow pointer
Browse files Browse the repository at this point in the history
when number of snips is 0, `end - 1` will go one below the
buffer. computing out of bound pointer (with the exception of
one past the end) is technically UB [0] so avoid it by doing the
computation on index instead of pointer.

0: https://port70.net/~nsz/c/c11/n1570.html#6.5.6p9
  • Loading branch information
N-R-K committed Jun 10, 2024
1 parent 1113ca8 commit 539547e
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/store.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stddef.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
Expand Down Expand Up @@ -567,18 +568,19 @@ bool cs_snip_iter(struct ref_guard *guard, enum cs_iter_direction direction,
}

struct cs_snip *start = guard->cs->snips;

// cppcheck-suppress [constVariablePointer,unmatchedSuppression]
// TODO: False positive? Report upstream
struct cs_snip *end = start + guard->cs->header->nr_snips;

ptrdiff_t idx, nr_snips = (ptrdiff_t)guard->cs->header->nr_snips;
if (*snip) {
*snip = *snip + (direction == CS_ITER_NEWEST_FIRST ? -1 : 1);
ptrdiff_t cur_idx = *snip - start;
idx = cur_idx + (direction == CS_ITER_NEWEST_FIRST ? -1 : 1);
} else {
*snip = direction == CS_ITER_NEWEST_FIRST ? end - 1 : start;
idx = direction == CS_ITER_NEWEST_FIRST ? nr_snips - 1 : 0;
}

return *snip >= start && *snip < end;
if (idx >= 0 && idx < nr_snips) {
*snip = start + idx;
return true;
}
return false;
}

/**
Expand Down

0 comments on commit 539547e

Please sign in to comment.