Skip to content

Commit 9d933ef

Browse files
committed
prevector: avoid misaligned member accesses
`#pragma pack(1)` prevents aligning the struct and its members to their required alignment. This can result in code that performs non-aligned reads and writes to integers and pointers, which is problematic on some architectures. It also triggers UBsan — see bitcoin/bitcoin#17156 (comment) and #17510.
1 parent 1189b6a commit 9d933ef

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/prevector.h

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
#include <type_traits>
1616
#include <utility>
1717

18-
#pragma pack(push, 1)
1918
/** Implements a drop-in replacement for std::vector<T> which stores up to N
2019
* elements directly (without heap allocation). The types Size and Diff are
2120
* used to store element counts, and can be any unsigned + signed type.
@@ -147,14 +146,20 @@ class prevector {
147146
};
148147

149148
private:
150-
size_type _size = 0;
149+
#pragma pack(push, 1)
151150
union direct_or_indirect {
152151
char direct[sizeof(T) * N];
153152
struct {
154-
size_type capacity;
155153
char* indirect;
154+
size_type capacity;
156155
};
157-
} _union = {};
156+
};
157+
#pragma pack(pop)
158+
alignas(char*) direct_or_indirect _union = {};
159+
size_type _size = 0;
160+
161+
static_assert(alignof(char*) % alignof(size_type) == 0 && sizeof(char*) % alignof(size_type) == 0, "size_type cannot have more restrictive alignment requirement than pointer");
162+
static_assert(alignof(char*) % alignof(T) == 0, "value_type T cannot have more restrictive alignment requirement than pointer");
158163

159164
T* direct_ptr(difference_type pos) { return reinterpret_cast<T*>(_union.direct) + pos; }
160165
const T* direct_ptr(difference_type pos) const { return reinterpret_cast<const T*>(_union.direct) + pos; }
@@ -523,6 +528,5 @@ class prevector {
523528
return item_ptr(0);
524529
}
525530
};
526-
#pragma pack(pop)
527531

528532
#endif // BITCOIN_PREVECTOR_H

0 commit comments

Comments
 (0)