Skip to content

Commit 6ad5fcb

Browse files
structclaude
andcommitted
Fix canary placement, bitmap buckets, printf, and assorted correctness bugs
Memory tagging: refresh a zone's tags once per threshold of allocations instead of on every free once the threshold is crossed. The refresh condition fixed in the previous commit made every idle free rewrite the whole tag array, a 1000x slowdown on that path. Canaries: pick any bitmap qword for a canary. Aligning the random index down restricted canaries to every 32nd qword, so a 1024 byte zone got at most 4 instead of 32 and small zones got 1. Zones: mlock the root mapping rather than the pointer to it. Walk size classes one at a time in find_suitable_zone, the geometric step skipped classes that already had a zone. Back the 16 byte bitmap bucket, which was never given a page so those zones always took a dedicated mapping. Widen the shared bitmap in_use field to 64 bits and cap the slices per page to its width, a 16K page holds up to 1024 slices and shifts past the width were undefined. Big zones: align the meta data offset after reducing it into range, and unmap the meta data page from its page boundary with a byte length. The old call passed a page count as the length with an unaligned pointer so it failed with EINVAL and leaked the page. Fix ALIGN_SZ_DOWN and ROUND_DOWN_PAGE, which rounded up and subtracted one unit, so an aligned value came back one unit short and zero underflowed. ROUND_DOWN_PAGE is used to find the page that holds big zone meta data, which can sit at offset 0 of its page. MTE: use size_t for the tag range loop so ranges over 2GB are tagged. calloc: return NULL instead of memset on a failed allocation. Destructor cleanup: do not munmap the thread local zone cache, and only destroy the sanity cache mutex when ALLOC_SANITY built it. This configuration did not compile before. CPU pinning: return -1 on macOS arm64. Current macOS no longer encodes the CPU number in tpidrro_el0 and the old mask only ever produced 0 or 8. Skip the core check in is_zone_usable when _iso_getcpu returns -1, so platforms that cannot report the CPU degrade to no pinning instead of rejecting every zone. NEON: gate USE_NEON on __aarch64__ since the intrinsics used are AArch64 only, keep the old UAF_PTR_PAGE_ODDS on non NEON targets where the scan did not get faster, factor the byte canary head and tail loops into one helper and document the little endian assumption. printf: rewrite _iso_alloc_printf with bounded output, correct signed handling for %d and %ld, %zu and %zd, NULL strings, %% and a documented argument width per conversion. The old version could read past the format string, dropped the character after a newline, copied strings unbounded into a 64K stack buffer and could never print a negative number. Fix the call sites that passed narrow types to %x. Tests: add printf_test and zone_internals_test to the test suite and rework tag_refresh_test for the once per threshold behaviour. Docs: describe the new tag refresh policy, note that CPU pinning is disabled on MacOS, document the AArch64 requirement for NEON and the UAF scan frequency, and add the tagging and profiler suites to the contributor checklist. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent eec439f commit 6ad5fcb

21 files changed

Lines changed: 707 additions & 203 deletions

‎CONTRIBUTE.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ Contributing to IsoAlloc is a pretty standard process of forking the repo, makin
1212

1313
`make cpp_tests` - Make sure all C++ tests still pass
1414

15+
`make tagging_tests MEMORY_TAGGING=-DMEMORY_TAGGING=1` - Make sure the memory tagging tests still pass
16+
17+
`make profiler_tests` - Make sure the heap profiler test still passes
18+
1519
`make library` - Build a release version of the library
1620

1721
`make cpp_library` - Build a release version of the library with C++ support

‎MEMORY_TAGGING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ These APIs can also be used in C, but this requires tagging and untagging pointe
4040
* All tag data is stored below user pages with a guard page allocated in between
4141
* A single 1 byte tag is generated per chunk in a private zone, this means the memory required to hold tags is larger for private zones holding smaller chunk sizes. For zones holding chunks 1024 byte or larger only a single of page of memory is required for tags as there are only 4096 possible 1024 byte chunks in 4mb IsoAlloc zone. The maximum amount of memory needed is for 16 byte chunks which requires 64 pages because there are 262144 possible chunks with a 4mb zone.
4242
* Tags are 1 byte in size and randomly chosen, they are added to the LSB of a pointer (e.g. tag value `0xed`, tagged pointer `0xed000b8066c1a000`, untagged pointer `0xb8066c1a000`)
43-
* Tags are refreshed whenever the private zone has reached %25 of 'retirement age' (defined in conf.h as `ZONE_ALLOC_RETIRE`) with 0 current allocations
43+
* Tags are refreshed each time the private zone has made allocations equal to %25 of 'retirement age' (defined in conf.h as `ZONE_ALLOC_RETIRE`) since the last refresh, and only while it has 0 current allocations
4444

4545
## Examples
4646

‎Makefile‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ PERM_FREE_REALLOC = -DPERM_FREE_REALLOC=0
2121
## 1 byte tag per addressable chunk of memory. These tags can
2222
## be retrieved and verified. This feature will likely interfere
2323
## with ARM MTE and PAC. See MEMORY_TAGGING.md for more information
24-
MEMORY_TAGGING = -DMEMORY_TAGGING=1
24+
MEMORY_TAGGING = -DMEMORY_TAGGING=0
2525

2626
## Enable abort() when isoalloc can't gather enough entropy.
2727
ABORT_NO_ENTROPY = -DABORT_NO_ENTROPY=1
@@ -430,6 +430,8 @@ tests: clean library_debug_unit_tests
430430
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) $(UNIT_TESTING) tests/uaf.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/uaf $(LDFLAGS)
431431
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) tests/interfaces_test.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/interfaces_test $(LDFLAGS)
432432
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) tests/aligned_alloc_test.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/aligned_alloc_test $(LDFLAGS)
433+
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) $(UNIT_TESTING) tests/zone_internals_test.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/zone_internals_test $(LDFLAGS)
434+
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) tests/printf_test.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/printf_test $(LDFLAGS)
433435
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) tests/thread_tests.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/thread_tests $(LDFLAGS)
434436
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) $(UNIT_TESTING) tests/big_canary_test.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/big_canary_test $(LDFLAGS)
435437
$(CC) $(CFLAGS) $(EXE_CFLAGS) $(DEBUG_LOG_FLAGS) $(GDB_FLAGS) $(OS_FLAGS) tests/big_tests.c $(ISO_ALLOC_PRINTF_SRC) -o $(BUILD_DIR)/big_tests $(LDFLAGS)

‎PERFORMANCE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ Zones are linked by their `next_sz_index` member which tells the allocator where
7979

8080
## ARM NEON
8181

82-
IsoAlloc tries to use ARM Neon instructions to make loops in the hot path faster. If you want to disable any of this code at compile time and rely instead on more portable, but potentially slower code just set `DONT_USE_NEON` to 1 in the Makefile.
82+
IsoAlloc tries to use ARM Neon instructions to make loops in the hot path faster. This code requires AArch64 as it uses across vector reductions that do not exist on 32 bit ARM. If you want to disable any of this code at compile time and rely instead on more portable, but potentially slower code just set `DONT_USE_NEON` to 1 in the Makefile. When `UAF_PTR_PAGE` is enabled the Neon version of the dangling pointer scan is fast enough that it runs 4x as often as the portable version, see `UAF_PTR_PAGE_ODDS` in `conf.h`.
8383

8484
## Tests
8585

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ See the [PERFORMANCE](PERFORMANCE.md) documentation for more information.
4444

4545
IsoAlloc is thread safe by way of protecting the root structure with a global lock built with either a pthread mutex, or a C11 `atomic_flag` when `USE_SPINLOCK` is enabled. This means every thread that wants to allocate or free a chunk needs to wait until it can take ownership of the lock. This design choice has some tradeoffs. It can negatively impact performance of multi threaded programs that perform a lot of allocations. This is because every thread shares the same set of global zones. The benefit of this is that you can allocate and free any chunk from any thread with no additional complexity required. In order to help alleviate contention on this lock each thread has a zone cache built using thread local storage (TLS). This is implemented as a simple FILO cache of the most recently used zones by that thread. It's size is 8 by default but can be increased modifying the `ZONE_CACHE_SZ` define in the internal header file. Making this cache too large can lead to negative performance implications for certain allocation patterns. For example, if a thread allocates multiple 32 byte chunks in a row then the cache may be populated entirely by the same zone that holds 32 byte chunks. Now when the thread goes to allocate a 64 byte chunk it iterates through the entire cache, does not find a usable zone, and then has to take the slow path which iterates through all zones again. This cache is also used when thread support is disabled but it does not live in TLS and is instead allocated on its own set of pages. See the [PERFORMANCE](PERFORMANCE.md) documentation for more information on the various caches in use in IsoAlloc.
4646

47-
When enabled, the `CPU_PIN` feature will restrict allocations from a given zone to the CPU core that created that zone. Free operations are not restricted in this way. This mode is compatible with and without thread support, but is only available on Linux, and will introduce a negative performance hit to the hot path and may increase memory usage. The benefit of this mode is that it introduces an isolation mechanism based on CPU core with no configuration beyond enabling the `CPU_PIN` define in the Makefile.
47+
When enabled, the `CPU_PIN` feature will restrict allocations from a given zone to the CPU core that created that zone. Free operations are not restricted in this way. This mode is compatible with and without thread support, but is only available on Linux, and will introduce a negative performance hit to the hot path and may increase memory usage. On MacOS the current core cannot be read from user space so pinning is silently disabled. The benefit of this mode is that it introduces an isolation mechanism based on CPU core with no configuration beyond enabling the `CPU_PIN` define in the Makefile.
4848

4949
## Security Properties
5050

‎include/compiler.h‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@
3838
#endif
3939
#endif
4040

41-
#if DONT_USE_NEON == 0 && __ARM_NEON
41+
/* The NEON paths use vmaxvq, an AArch64 only across
42+
* vector reduction, so 32 bit ARM with NEON is excluded */
43+
#if DONT_USE_NEON == 0 && __ARM_NEON && __aarch64__
4244
#include <arm_neon.h>
4345
#define USE_NEON 1
4446
#else

‎include/conf.h‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,18 @@
4242
#endif
4343

4444
/* If you're using the UAF_PTR_PAGE functionality and
45-
* want to change the frequency it is triggered */
45+
* want to change the frequency it is triggered. Each
46+
* trigger scans every zone under the root lock. The
47+
* NEON scan is fast enough to run 4x as often, other
48+
* targets keep the original frequency */
4649
#if UAF_PTR_PAGE
50+
/* This mirrors the USE_NEON condition in compiler.h, which
51+
* is included after this file so USE_NEON is not visible yet */
52+
#if DONT_USE_NEON == 0 && __ARM_NEON && __aarch64__
4753
#define UAF_PTR_PAGE_ODDS 250000
54+
#else
55+
#define UAF_PTR_PAGE_ODDS 1000000
56+
#endif
4857
#endif
4958

5059
/* Zones can be retired after a certain number of

‎include/iso_alloc_ds.h‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,13 @@ typedef struct {
5050
uint8_t cpu_core; /* What CPU core this zone is pinned to */
5151
#endif
5252
/* Warm/cold fields: accessed less frequently */
53-
uint16_t bitmap_size; /* Size of the bitmap in bytes */
54-
uint32_t af_count; /* Increment/Decrement with each alloc/free operation */
55-
uint32_t chunk_count; /* Total number of chunks in this zone */
56-
uint32_t alloc_count; /* Total number of lifetime allocations */
53+
uint16_t bitmap_size; /* Size of the bitmap in bytes */
54+
uint32_t af_count; /* Increment/Decrement with each alloc/free operation */
55+
uint32_t chunk_count; /* Total number of chunks in this zone */
56+
uint32_t alloc_count; /* Total number of lifetime allocations */
57+
#if MEMORY_TAGGING
58+
uint32_t tags_refreshed_at; /* Value of alloc_count at the last whole zone tag refresh */
59+
#endif
5760
uint16_t index; /* Zone index */
5861
uint16_t next_sz_index; /* What is the index of the next zone of this size */
5962
/* Large cold array: only accessed when refilling the free list */
@@ -101,7 +104,7 @@ const static int small_bitmap_sizes[] = {
101104
typedef struct {
102105
void *bitmap;
103106
/* Our bitmap has a bitmap */
104-
uint32_t in_use;
107+
uint64_t in_use; /* One bit per bitmap slice handed out from this page */
105108
/* Bucket value determines how many times we divy up
106109
* the bitmap page. eg For BITMAP_SIZE_16 its 256 times */
107110
uint32_t bucket;

‎include/iso_alloc_internal.h‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,14 +197,21 @@ assert(sizeof(size_t) >= 64)
197197
#define ALIGN_SZ_UP(n) \
198198
((n + SZ_ALIGNMENT - 1) & ~(SZ_ALIGNMENT - 1))
199199

200+
/* Rounds n down to a multiple of SZ_ALIGNMENT. The previous
201+
* definition rounded up and subtracted SZ_ALIGNMENT, which
202+
* returned n - SZ_ALIGNMENT for an already aligned n and
203+
* underflowed for 0 */
200204
#define ALIGN_SZ_DOWN(n) \
201-
(((n + SZ_ALIGNMENT - 1) & ~(SZ_ALIGNMENT - 1)) - SZ_ALIGNMENT)
205+
((n) & ~((__typeof__(n)) (SZ_ALIGNMENT - 1)))
202206

203207
#define ROUND_UP_PAGE(n) \
204208
((((n + g_page_size) - 1) >> g_page_size_shift) * (g_page_size))
205209

210+
/* Rounds n down to a page boundary. The previous definition
211+
* rounded up and subtracted a page, which returned the page
212+
* before n when n was already page aligned */
206213
#define ROUND_DOWN_PAGE(n) \
207-
(ROUND_UP_PAGE(n) - g_page_size)
214+
((n) & ~((__typeof__(n)) (g_page_size - 1)))
208215

209216
#if MASK_PTRS
210217
#define MASK_ZONE_PTRS(zone) \

‎include/iso_alloc_util.h‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ INTERNAL_HIDDEN int32_t name_mapping(void *p, size_t sz, const char *name);
3434
INTERNAL_HIDDEN size_t next_pow2(size_t sz);
3535
INTERNAL_HIDDEN uint32_t _log2(uint32_t v);
3636

37-
INTERNAL_HIDDEN int8_t *_fmt(uint64_t n, uint32_t base);
3837
INTERNAL_HIDDEN void _iso_alloc_printf(int32_t fd, const char *f, ...);
3938

4039
#if CPU_PIN

0 commit comments

Comments
 (0)