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

[PATCH v2 2/2] mem: Align heap allocations for pointers too



zhalloc() rounds the size of each allocation up to a multiple of
sizeof(union mem_align). As the union only holds a zlong and a double,
this is 8 bytes on common platforms. Allocations are carved
consecutively out of an arena, so their start addresses are only
guaranteed to be 8-byte aligned.

On CHERI [1, 2], pointers are capabilities, which on 64-bit systems are
16 bytes in size and must be 16-byte aligned. Loading or storing a
pointer in a heap allocation that is only 8-byte aligned therefore
faults.

Add a void * member to union mem_align, so that heap allocations are
suitably aligned for pointers too. The arena itself starts right after
struct heap, whose size is a multiple of the pointer alignment as it
contains pointers, so no further change is needed. This also raises the
block alignment (M_ALIGN) of the optional ZSH_MEM allocator accordingly.
On platforms where pointers are no larger than zlong and double, the
size of the union, and thus the heap layout, remains unchanged.

Aligning to _Alignof(max_align_t) instead, as malloc() does, was
considered. However, heap memory only holds zsh's own data, which needs
no more alignment than zlong, double and pointers. Moreover, it would
change the heap layout on common platforms such as x86_64, where
_Alignof(max_align_t) is 16 rather than 8, and the arena start would
need padding, as sizeof(struct heap) is not always a multiple of 16.
This is left for a separate change.

1: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
2: https://codasip.com/solutions/riscv-processor-safety-security/cheri/
---
 Src/mem.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/Src/mem.c b/Src/mem.c
index 30562f421c93..77ac95ae7a88 100644
--- a/Src/mem.c
+++ b/Src/mem.c
@@ -113,6 +113,7 @@ static int h_m[1025], h_push, h_pop, h_free;
 union mem_align {
     zlong l;
     double d;
+    void *p;
 };
 
 #define H_ISIZE  sizeof(union mem_align)
@@ -1035,8 +1036,9 @@ zrealloc(void *ptr, size_t size)
 /*
    Below is a simple segment oriented memory allocator for systems on
    which it is better than the system's one. Memory is given in blocks
-   aligned to an integer multiple of sizeof(union mem_align), which will
-   probably be 64-bit as it is the longer of zlong or double. Each block is
+   aligned to an integer multiple of sizeof(union mem_align), which is the
+   largest of zlong, double and void *. This is 64-bit on most platforms,
+   but 128-bit on 64-bit CHERI, where pointers are capabilities. Each block is
    preceded by a header which contains the length of the data part (in
    bytes). In allocated blocks only this field of the structure m_hdr is
    senseful. In free blocks the second field (next) is a pointer to the next
-- 
2.56.1





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