Skip to content

Commit 7945755

Browse files
committed
Address overflow cases in init
1 parent bde7ae4 commit 7945755

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

libc/src/__support/block.h

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -41,24 +41,10 @@ LIBC_INLINE constexpr size_t align_down(size_t value, size_t alignment) {
4141
return (value / alignment) * alignment;
4242
}
4343

44-
/// Returns the value rounded down to the nearest multiple of alignment.
45-
template <typename T>
46-
LIBC_INLINE constexpr T *align_down(T *value, size_t alignment) {
47-
return reinterpret_cast<T *>(
48-
align_down(reinterpret_cast<size_t>(value), alignment));
49-
}
50-
51-
/// Returns the value rounded up to the nearest multiple of alignment.
44+
/// Returns the value rounded up to the nearest multiple of alignment. May wrap
45+
/// around.
5246
LIBC_INLINE constexpr size_t align_up(size_t value, size_t alignment) {
53-
__builtin_add_overflow(value, alignment - 1, &value);
54-
return align_down(value, alignment);
55-
}
56-
57-
/// Returns the value rounded up to the nearest multiple of alignment.
58-
template <typename T>
59-
LIBC_INLINE constexpr T *align_up(T *value, size_t alignment) {
60-
return reinterpret_cast<T *>(
61-
align_up(reinterpret_cast<size_t>(value), alignment));
47+
return align_down(value + alignment - 1, alignment);
6248
}
6349

6450
using ByteSpan = cpp::span<LIBC_NAMESPACE::cpp::byte>;
@@ -326,6 +312,7 @@ class Block {
326312
// undefined if allocation is not possible for the given size and alignment.
327313
static BlockInfo allocate(Block *block, size_t alignment, size_t size);
328314

315+
// These two functions may wrap around.
329316
LIBC_INLINE static uintptr_t next_possible_block_start(
330317
uintptr_t ptr, size_t usable_space_alignment = alignof(max_align_t)) {
331318
return align_up(ptr + sizeof(Block), usable_space_alignment) -
@@ -377,9 +364,17 @@ optional<Block *> Block::init(ByteSpan region) {
377364

378365
uintptr_t start = reinterpret_cast<uintptr_t>(region.data());
379366
uintptr_t end = start + region.size();
367+
if (end < start)
368+
return {};
380369

381370
uintptr_t block_start = next_possible_block_start(start);
371+
if (block_start < start)
372+
return {};
373+
382374
uintptr_t last_start = prev_possible_block_start(end);
375+
if (last_start >= end)
376+
return {};
377+
383378
if (block_start + sizeof(Block) > last_start)
384379
return {};
385380

0 commit comments

Comments
 (0)