Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

[PATCH v2 1/2] mem: Check that sizeof(union mem_align) is a power of two



zhalloc() and hrealloc() round sizes up to a multiple of H_ISIZE using
(size + H_ISIZE - 1) & ~(H_ISIZE - 1). The optional ZSH_MEM allocator
does the same with M_ALIGN, which has the same value, and also uses
M_ALIGN - 1 as a mask to test the alignment of addresses. These masks
only work as intended if sizeof(union mem_align) is a power of two,
which nothing guarantees.

If it were not, the rounding would still never round down and would
still yield multiples of the union's alignment, so zhalloc() would keep
working. However, ZSH_MEM's free() could reject valid pointers, as its
"(long)p & (M_ALIGN - 1)" check would misfire.

Add a compile-time check, so that such a platform fails to build
instead of silently misbehaving.
---
 Src/mem.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/Src/mem.c b/Src/mem.c
index 0b6f76e46b2b..30562f421c93 100644
--- a/Src/mem.c
+++ b/Src/mem.c
@@ -124,6 +124,13 @@ union mem_align {
 /* Memory available for user data in heap h */
 #define ARENA_SIZEOF(h) ((h)->size - sizeof(struct heap))
 
+/*
+ * Sizes and addresses are rounded to multiples of H_ISIZE (and of M_ALIGN,
+ * which is the same) using bit masks, which only works for powers of two.
+ */
+typedef char mem_align_size_is_power_of_two
+    [(H_ISIZE & (H_ISIZE - 1)) == 0 ? 1 : -1];
+
 /* list of zsh heaps */
 
 static Heap heaps;
-- 
2.56.1





Messages sorted by: Reverse Date, Date, Thread, Author