AP_Common: add sanity check into bitmask get/set

Also return false if we are asked about an out-of-bounds bit
This commit is contained in:
Peter Barker 2019-04-16 14:48:16 +10:00 committed by Andrew Tridgell
parent fbc2650449
commit 9d4bdbf3d5
2 changed files with 11 additions and 0 deletions

View File

@ -21,6 +21,8 @@
#include <stdint.h>
#include <string.h>
#include <AP_InternalError/AP_InternalError.h>
template<uint16_t num_bits>
class Bitmask {
public:
@ -41,6 +43,7 @@ public:
void set(uint16_t bit) {
// ignore an invalid bit number
if (bit >= numbits) {
AP::internalerror().error(AP_InternalError::error_t::bitmask_range);
return;
}
uint16_t word = bit/32;
@ -75,6 +78,12 @@ public:
bool get(uint16_t bit) const {
uint16_t word = bit/32;
uint8_t ofs = bit & 0x1f;
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
if (bit >= numbits) {
AP::internalerror().error(AP_InternalError::error_t::bitmask_range);
return false;
}
#endif
return (bits[word] & (1U << ofs)) != 0;
}

View File

@ -75,3 +75,5 @@ TEST(Bitmask, Assignment)
}
AP_GTEST_MAIN()
int hal = 0; // bizarrely, this fixes an undefined-symbol error but doesn't raise a type exception. Yay.