5 void *aligned_alloc(size_t align, size_t len)
7 if ((align & -align) != align) {
12 if (len > SIZE_MAX - align || align >= (1ULL<<31)*UNIT) {
17 if (DISABLE_ALIGNED_ALLOC) {
22 if (align <= UNIT) align = UNIT;
24 unsigned char *p = malloc(len + align - UNIT);
28 struct meta *g = get_meta(p);
29 int idx = get_slot_index(p);
30 size_t stride = get_stride(g);
31 unsigned char *start = g->mem->storage + stride*idx;
32 unsigned char *end = g->mem->storage + stride*(idx+1) - IB;
33 size_t adj = -(uintptr_t)p & (align-1);
36 set_size(p, end, len);
40 uint32_t offset = (size_t)(p-g->mem->storage)/UNIT;
41 if (offset <= 0xffff) {
42 *(uint16_t *)(p-2) = offset;
45 // use a 32-bit offset if 16-bit doesn't fit. for this,
46 // 16-bit field must be zero, [-4] byte nonzero.
47 *(uint16_t *)(p-2) = 0;
48 *(uint32_t *)(p-8) = offset;
52 set_size(p, end, len);
53 // store offset to aligned enframing. this facilitates cycling
54 // offset and also iteration of heap for debugging/measurement.
55 // for extreme overalignment it won't fit but these are classless
56 // allocations anyway.
57 *(uint16_t *)(start - 2) = (size_t)(p-start)/UNIT;