From cdf6f5ae0465a8fb25d2afc758911985cc542a07 Mon Sep 17 00:00:00 2001 From: Tom Gundersen Date: Fri, 17 Jul 2015 18:30:41 +0200 Subject: basic: bitmap - complete fix for bitshift overflow The bug found by David existed in several places, fix them all. Also extend the tests to cover these cases. --- src/basic/bitmap.c | 14 +++++++------- src/test/test-bitmap.c | 8 ++++++++ 2 files changed, 15 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/basic/bitmap.c b/src/basic/bitmap.c index c5039fd22f..0747749d13 100644 --- a/src/basic/bitmap.c +++ b/src/basic/bitmap.c @@ -69,7 +69,7 @@ int bitmap_ensure_allocated(Bitmap **b) { } int bitmap_set(Bitmap *b, unsigned n) { - long long bitmask; + long long unsigned bitmask; unsigned offset; assert(b); @@ -87,7 +87,7 @@ int bitmap_set(Bitmap *b, unsigned n) { b->n_bitmaps = offset + 1; } - bitmask = 1 << BITMAP_NUM_TO_REM(n); + bitmask = 1ULL << BITMAP_NUM_TO_REM(n); b->bitmaps[offset] |= bitmask; @@ -95,7 +95,7 @@ int bitmap_set(Bitmap *b, unsigned n) { } void bitmap_unset(Bitmap *b, unsigned n) { - long long bitmask; + long long unsigned bitmask; unsigned offset; assert(b); @@ -105,13 +105,13 @@ void bitmap_unset(Bitmap *b, unsigned n) { if (offset >= b->n_bitmaps) return; - bitmask = 1 << BITMAP_NUM_TO_REM(n); + bitmask = 1ULL << BITMAP_NUM_TO_REM(n); b->bitmaps[offset] &= ~bitmask; } bool bitmap_isset(Bitmap *b, unsigned n) { - long long bitmask; + long long unsigned bitmask; unsigned offset; if (!b || !b->bitmaps) @@ -122,7 +122,7 @@ bool bitmap_isset(Bitmap *b, unsigned n) { if (offset >= b->n_bitmaps) return false; - bitmask = 1 << BITMAP_NUM_TO_REM(n); + bitmask = 1ULL << BITMAP_NUM_TO_REM(n); return !!(b->bitmaps[offset] & bitmask); } @@ -149,7 +149,7 @@ void bitmap_clear(Bitmap *b) { } bool bitmap_iterate(Bitmap *b, Iterator *i, unsigned *n) { - long long bitmask; + long long unsigned bitmask; unsigned offset, rem; if (!b || i->idx == BITMAP_END) diff --git a/src/test/test-bitmap.c b/src/test/test-bitmap.c index 77db784a94..96deeded7e 100644 --- a/src/test/test-bitmap.c +++ b/src/test/test-bitmap.c @@ -58,6 +58,14 @@ int main(int argc, const char *argv[]) { assert_se(bitmap_isset(b, 256) == false); assert_se(bitmap_isclear(b) == true); + assert_se(bitmap_set(b, 32) == 0); + bitmap_unset(b, 0); + assert_se(bitmap_isset(b, 32) == true); + bitmap_unset(b, 32); + + BITMAP_FOREACH(n, NULL, it) + assert_not_reached("NULL bitmap"); + assert_se(bitmap_set(b, 0) == 0); assert_se(bitmap_set(b, 1) == 0); assert_se(bitmap_set(b, 256) == 0); -- cgit v1.2.3-54-g00ecf