diff --git a/.github/workflows/testsuite.yml b/.github/workflows/testsuite.yml index 02a8291..152a714 100644 --- a/.github/workflows/testsuite.yml +++ b/.github/workflows/testsuite.yml @@ -7,19 +7,22 @@ jobs: - uses: actions/checkout@v2 - run: make tests - run: make cpp_tests + - run: make preload_tests testsuite-clang: runs-on: ubuntu-latest strategy: matrix: - version: [15, 16, 17, 18] + version: [17, 18, 19, 20, 21] steps: - uses: actions/checkout@v4 - run: | + sudo apt-get update sudo apt install clang-${{ matrix.version }} sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-${{ matrix.version }} 100 sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-${{ matrix.version }} 100 - run: make tests - run: make cpp_tests + - run: make preload_tests testsuite-clang18-perf: runs-on: ubuntu-latest steps: @@ -38,6 +41,7 @@ jobs: - uses: actions/checkout@v4 - run: make tests CC=gcc CXX=g++ - run: make cpp_tests CC=gcc CXX=g++ + - run: make preload_tests CC=gcc CXX=g++ testsuite-musl: runs-on: ubuntu-latest container: diff --git a/Makefile b/Makefile index d5fffcc..d5cc211 100644 --- a/Makefile +++ b/Makefile @@ -262,11 +262,17 @@ STDC=c11 LTO = -flto LIBNAME = libisoalloc.so +SOEXT = so +## Shared libraries built for the preload tests get an rpath +## relative install name on macOS so dyld finds them from any cwd +PRELOAD_LIB_FLAGS = UNAME := $(shell uname) ifeq ($(UNAME), Darwin) OS_FLAGS = LIBNAME = libisoalloc.dylib +SOEXT = dylib +PRELOAD_LIB_FLAGS = -Wl,-install_name,@rpath/libpreload_exit_order.dylib ifeq ($(MEMCPY_SANITY), -DMEMCPY_SANITY=1) CFLAGS += -D_FORTIFY_SOURCE=0 endif @@ -546,6 +552,31 @@ endif @echo "Running system malloc Performance Test" build/malloc_tests +## Preload tests. Builds the release library with the C and C++ +## hooks, then builds programs that do not link it at all and runs +## them with the library inserted the way a user would: LD_PRELOAD +## on Linux, DYLD_INSERT_LIBRARIES on macOS. They check that every +## allocation entry point is taken over, that pointers from the +## system allocator are handled, that fork and threads are safe +## and that other libraries can allocate from their destructors. +## Pass ABORT_ON_UNOWNED_PTR=-DABORT_ON_UNOWNED_PTR=0 to run them +## against the less strict configuration too. +PRELOAD_TEST_CFLAGS = -O1 -Wall -pthread $(OS_FLAGS) +preload_tests: cpp_library + @echo "make preload_tests" + $(CC) $(PRELOAD_TEST_CFLAGS) tests/preload/interpose_check.c -o $(BUILD_DIR)/preload_interpose_check -ldl + $(CC) $(PRELOAD_TEST_CFLAGS) tests/preload/foreign_ptr.c -o $(BUILD_DIR)/preload_foreign_ptr -ldl + $(CC) $(PRELOAD_TEST_CFLAGS) tests/preload/fork_safety.c -o $(BUILD_DIR)/preload_fork_safety -ldl + $(CC) $(PRELOAD_TEST_CFLAGS) tests/preload/thread_churn.c -o $(BUILD_DIR)/preload_thread_churn -ldl + $(CXX) -std=$(STDCXX) $(PRELOAD_TEST_CFLAGS) tests/preload/cpp_hooks.cpp -o $(BUILD_DIR)/preload_cpp_hooks -ldl + $(CC) $(PRELOAD_TEST_CFLAGS) -fPIC -shared $(PRELOAD_LIB_FLAGS) tests/preload/exit_order_lib.c -o $(BUILD_DIR)/libpreload_exit_order.$(SOEXT) + $(CC) $(PRELOAD_TEST_CFLAGS) tests/preload/exit_order_main.c -L$(BUILD_DIR) -lpreload_exit_order -Wl,-rpath,$(abspath $(BUILD_DIR)) -o $(BUILD_DIR)/preload_exit_order -ldl + bash utils/run_preload_tests.sh $(BUILD_DIR)/$(LIBNAME) "$(THREAD_SUPPORT)" + +## The macOS specific name for the same thing. Interposing and the +## malloc zone only exist there, see malloc_hook.c +test_macos: preload_tests + ## C++ Support - Build a debug version of the unit test cpp_tests: clean cpp_library_debug @echo "make cpp_tests" @@ -556,10 +587,10 @@ install: cp -pR build/$(LIBNAME) /usr/lib/ format: - clang-format-18 $(SRC_DIR)/*.* tests/*.* include/*.h -i + clang-format-18 $(SRC_DIR)/*.* tests/*.* tests/preload/*.* include/*.h -i format-ci: - clang-format-18 --Werror --dry-run $(SRC_DIR)/*.* tests/*.* include/*.h -i + clang-format-18 --Werror --dry-run $(SRC_DIR)/*.* tests/*.* tests/preload/*.* include/*.h -i clean: rm -rf build/* tests_perf_analysis.txt big_tests_perf_analysis.txt gmon.out \ diff --git a/README.md b/README.md index 50a3f82..99709a8 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,9 @@ The Makefile targets are very simple: `make library` - Builds a release version of the library without C++ support -`make library_less_strict` - Builds a release library with `ABORT_ON_UNOWNED_PTR=0`. Recommended when using IsoAlloc via `LD_PRELOAD`. +`make library_less_strict` - Builds a release library with `ABORT_ON_UNOWNED_PTR=0`. Recommended when using IsoAlloc via `LD_PRELOAD` or `DYLD_INSERT_LIBRARIES` with programs that hand pointers from other allocators to `free`. + +`make preload_tests` - Builds the release library and runs programs that do not link it with the library preloaded, see [Using IsoAlloc As The System Allocator](#using-isoalloc-as-the-system-allocator). `make library_debug` - Builds a debug version of the library @@ -143,6 +145,22 @@ or If you want to use IsoAlloc with a C++ program you can use the `c_library_objects` Makefile target. This will produce .o object files you can pass to your compiler. These targets are used internally to build the library with `new` and `delete` support. +## Using IsoAlloc As The System Allocator + +The library built by `make library` (or `make cpp_library` for `new` and `delete` as well) takes over `malloc`, `calloc`, `realloc`, `reallocarray`, `free`, `posix_memalign`, `aligned_alloc`, `memalign`, `valloc`, `pvalloc` and `malloc_usable_size` in any program it is loaded into, so it can be used with existing and closed source programs without recompiling them. + +On Linux use `LD_PRELOAD=/path/to/libisoalloc.so `. The hooks are linker aliases for the `iso_` functions. + +On macOS use `DYLD_INSERT_LIBRARIES=/path/to/libisoalloc.dylib `. Every image on macOS is linked with a two level namespace, so a dylib that merely defines `malloc` is never called, and `DYLD_FORCE_FLAT_NAMESPACE` no longer changes that. Instead the library carries a `__DATA,__interpose` table that makes dyld rebind every image's references to the libSystem allocator (`malloc`, `calloc`, `realloc`, `reallocf`, `free`, `posix_memalign`, `aligned_alloc`, `valloc`, `malloc_size`, `malloc_good_size`, the typed `malloc_type_*` entry points and the C++ operators) to IsoAlloc. It also registers a `malloc_zone_t` and makes it the default zone, so `malloc_zone_malloc(malloc_default_zone(), ...)`, `malloc_zone_from_ptr`, `malloc_zone_free` and the rest of the zone API recognize IsoAlloc chunks, and libSystem drives IsoAlloc's `fork()` handlers through it. The same interpose table applies when a program is linked against the dylib directly. Some things to know on macOS: + +* System Integrity Protection strips `DYLD_INSERT_LIBRARIES` from platform binaries such as `/usr/bin/python3`, silently. The program runs with the system allocator. Use a binary you built or installed yourself, for example from Homebrew. +* Applications with the hardened runtime need the `com.apple.security.cs.allow-dyld-environment-variables` entitlement, and ones with library validation only load dylibs signed by the same team. +* libSystem allocates before IsoAlloc's constructor runs and frameworks such as CoreFoundation allocate from their own zones, so pointers from the system allocator reach `free`, `realloc` and `malloc_size`. IsoAlloc hands those back to the zone that owns them, and `realloc` migrates them into IsoAlloc. Only a pointer that no allocator owns is treated as an error, which `ABORT_ON_UNOWNED_PTR` controls as usual. + +On both platforms IsoAlloc is usually initialized by the first allocation rather than by its constructor, and `fork()` is safe while other threads allocate: on Linux through `pthread_atfork`, on macOS through the malloc zone callbacks. The library's destructor leaves all memory mapped unless `ISO_DTOR_CLEANUP` is set, because destructors of other libraries run after it and still use their allocations. + +`make preload_tests` (or `make test_macos`, the same target) builds the library and a set of programs that do not link it, then runs them with the library inserted. They check every entry point is taken over, that pointers from the system allocator work, that threads and `fork()` are safe, that C++ operators are replaced, and that another library can allocate from its destructor. Run it with `ABORT_ON_UNOWNED_PTR=-DABORT_ON_UNOWNED_PTR=0` to cover the less strict configuration as well. A library built with `THREAD_SUPPORT=-DTHREAD_SUPPORT=0` only runs the single threaded programs. + ## Debugging If you try to use Isolation Alloc in an existing program then and you are getting crashes here are some tips to help you get started. If you aren't using `LD_PRELOAD` then first make sure you actually replaced all `malloc, calloc, realloc` and `free` calls to their `iso_alloc` equivalents. Don't forget things like `strdup` that return a pointer from `malloc`. diff --git a/include/iso_alloc_internal.h b/include/iso_alloc_internal.h index ea5f46f..9337f90 100644 --- a/include/iso_alloc_internal.h +++ b/include/iso_alloc_internal.h @@ -563,9 +563,22 @@ INTERNAL_HIDDEN uint8_t _iso_alloc_get_mem_tag(void *p, iso_alloc_zone_t *zone); INTERNAL_HIDDEN void _iso_alloc_verify_tag(void *p, iso_alloc_zone_t *zone); INTERNAL_HIDDEN size_t _iso_alloc_print_stats(void); INTERNAL_HIDDEN size_t _iso_chunk_size(void *p); +INTERNAL_HIDDEN bool _iso_alloc_chunk_lookup(void *p, size_t *size); INTERNAL_HIDDEN int64_t check_canary_no_abort(iso_alloc_zone_t *zone, const void *p); INTERNAL_HIDDEN void _iso_alloc_initialize(void); INTERNAL_HIDDEN void _iso_alloc_destroy(void); +#if THREAD_SUPPORT +INTERNAL_HIDDEN void _iso_alloc_fork_prepare(void); +INTERNAL_HIDDEN void _iso_alloc_fork_parent(void); +INTERNAL_HIDDEN void _iso_alloc_fork_child(void); +#endif +#if __APPLE__ && MALLOC_HOOK +/* The macOS hook layer, see malloc_hook.c */ +INTERNAL_HIDDEN void _iso_alloc_darwin_zone_init(void); +INTERNAL_HIDDEN void _iso_alloc_darwin_free(void *p); +INTERNAL_HIDDEN void _iso_alloc_darwin_free_size(void *p, size_t size); +INTERNAL_HIDDEN void *_iso_alloc_darwin_realloc(void *p, size_t size); +#endif #ifdef __cplusplus } #endif diff --git a/include/os/macos.h b/include/os/macos.h index f5f4c89..b5cdb1c 100644 --- a/include/os/macos.h +++ b/include/os/macos.h @@ -9,13 +9,3 @@ #define bswap_32(x) OSSwapInt32(x) #define bswap_64(x) OSSwapInt64(x) #define ENVIRON NULL - -/* - * On pthread_exit, it expects to be dealing with libmalloc - * rather than isoalloc at releasing time - */ -__attribute__((weak)) void _pthread_tsd_cleanup(pthread_t); -void _pthread_tsd_cleanup(pthread_t p) -{ - (void)p; -} diff --git a/src/iso_alloc.c b/src/iso_alloc.c index 49448fe..1520c4d 100644 --- a/src/iso_alloc.c +++ b/src/iso_alloc.c @@ -13,7 +13,11 @@ #if USE_SPINLOCK atomic_flag root_busy_flag; #else -pthread_mutex_t root_busy_mutex; +/* Statically initialized so it is valid before any init path + * runs. A zero filled pthread_mutex_t is not a usable mutex on + * every platform, on macOS locking one fails with EINVAL and + * silently does nothing */ +pthread_mutex_t root_busy_mutex = PTHREAD_MUTEX_INITIALIZER; #endif uint32_t g_page_size; @@ -204,6 +208,9 @@ INTERNAL_HIDDEN void iso_alloc_initialize_global_root(void) { return; } + g_page_size = sysconf(_SC_PAGESIZE); + g_page_size_shift = _log2(g_page_size); + _root = iso_alloc_new_root(); if(_root == NULL) { @@ -214,6 +221,14 @@ INTERNAL_HIDDEN void iso_alloc_initialize_global_root(void) { * result in a soft page fault */ MLOCK(_root, sizeof(iso_alloc_root)); +#if THREAD_SUPPORT && !USE_SPINLOCK + /* The root is fresh from mmap and these must be valid + * before anything can take them, whichever init path + * created the root */ + pthread_mutex_init(&_root->big_zone_free_mutex, NULL); + pthread_mutex_init(&_root->big_zone_used_mutex, NULL); +#endif + #if ARM_MTE if(iso_is_mte_supported() == false) { _root->arm_mte_enabled = false; @@ -311,27 +326,12 @@ INTERNAL_HIDDEN void iso_alloc_initialize_global_root(void) { _root->zone_handle_mask = rand_uint64(); _root->big_zone_next_mask = us_rand_uint64(&_root->seed); _root->big_zone_canary_secret = us_rand_uint64(&_root->seed); -} - -INTERNAL_HIDDEN void _iso_alloc_initialize(void) { - if(_root != NULL) { - return; - } - - g_page_size = sysconf(_SC_PAGESIZE); - g_page_size_shift = _log2(g_page_size); - - iso_alloc_initialize_global_root(); - -#if THREAD_SUPPORT && !USE_SPINLOCK - pthread_mutex_init(&root_busy_mutex, NULL); - pthread_mutex_init(&_root->big_zone_free_mutex, NULL); - pthread_mutex_init(&_root->big_zone_used_mutex, NULL); -#if ALLOC_SANITY - pthread_mutex_init(&sane_cache_mutex, NULL); -#endif -#endif + /* Everything below used to run only from the constructor. + * When a caller beats the constructor, which is the normal + * case under LD_PRELOAD and DYLD_INSERT_LIBRARIES, the + * root was created lazily and all of this was skipped, so + * malloc(0) returned NULL for the life of the process */ #if HEAP_PROFILER _initialize_profiler(); #endif @@ -364,6 +364,50 @@ INTERNAL_HIDDEN void _iso_alloc_initialize(void) { #endif } +/* Work that needs the root but must not run under the root + * lock, because it calls into libc or the system allocator + * which may allocate. Runs once, from whichever init path + * created the root, after that path released the lock */ +static void post_root_init(void) { +#if THREAD_SUPPORT + static atomic_flag done; + + if(atomic_flag_test_and_set(&done)) { + return; + } +#else + static bool done; + + if(done == true) { + return; + } + + done = true; +#endif + +#if __APPLE__ && MALLOC_HOOK + /* Registers the malloc zone, which also gives us the + * libSystem fork callbacks */ + _iso_alloc_darwin_zone_init(); +#elif THREAD_SUPPORT + pthread_atfork(_iso_alloc_fork_prepare, _iso_alloc_fork_parent, _iso_alloc_fork_child); +#endif +} + +INTERNAL_HIDDEN void _iso_alloc_initialize(void) { + if(_root == NULL) { + LOCK_ROOT(); + + if(_root == NULL) { + iso_alloc_initialize_global_root(); + } + + UNLOCK_ROOT(); + } + + post_root_init(); +} + #if AUTO_CTOR_DTOR __attribute__((destructor(LAST_DTOR))) void iso_alloc_dtor(void) { _iso_alloc_destroy(); @@ -1680,8 +1724,6 @@ static __attribute__((cold, noinline)) void initialize_root_slow(iso_alloc_zone_ LOG_AND_ABORT("_root was NULL but zone %p was not", zone); } - g_page_size = sysconf(_SC_PAGESIZE); - g_page_size_shift = _log2(g_page_size); iso_alloc_initialize_global_root(); #else LOG_AND_ABORT("Root never initialized!"); @@ -1689,6 +1731,7 @@ static __attribute__((cold, noinline)) void initialize_root_slow(iso_alloc_zone_ } UNLOCK_ROOT(); + post_root_init(); } INTERNAL_HIDDEN ASSUME_ALIGNED void *_iso_alloc(iso_alloc_zone_t *zone, size_t size) { @@ -2242,6 +2285,13 @@ INTERNAL_HIDDEN void _iso_free(void *p, bool permanent) { return; } + /* A free before the first allocation can only name a + * pointer we do not own, but the lookups below need a + * root to say so */ + if(UNLIKELY(_root == NULL)) { + initialize_root_slow(NULL); + } + /* All pointers to chunks should be 8 byte aligned. * This is true whether its big zone or not */ if(UNLIKELY(IS_ALIGNED((uintptr_t) p) != 0)) { @@ -2314,6 +2364,10 @@ INTERNAL_HIDDEN void _iso_free_size(void *p, size_t size) { return; } + if(UNLIKELY(_root == NULL)) { + initialize_root_slow(NULL); + } + #if NO_ZERO_ALLOCATIONS if(UNLIKELY(p == _root->zero_alloc_page && size != 0)) { LOG_AND_ABORT("Zero sized chunk (0x%p) with non-zero (%d) size passed to free", p, size); @@ -2865,14 +2919,24 @@ INTERNAL_HIDDEN void _iso_alloc_unprotect_root(void) { UNLOCK_ROOT(); } -INTERNAL_HIDDEN size_t _iso_chunk_size(void *p) { +/* Says whether p is a chunk this allocator handed out and if + * so how large it is. Never aborts, so the hook layer can tell + * a pointer from another allocator apart from a wild one. A + * NULL p and the zero allocation page are owned with size 0 */ +INTERNAL_HIDDEN bool _iso_alloc_chunk_lookup(void *p, size_t *size) { + *size = 0; + if(p == NULL) { - return 0; + return true; + } + + if(UNLIKELY(_root == NULL)) { + initialize_root_slow(NULL); } #if NO_ZERO_ALLOCATIONS if(UNLIKELY(p == _root->zero_alloc_page)) { - return 0; + return true; } #endif @@ -2881,9 +2945,9 @@ INTERNAL_HIDDEN size_t _iso_chunk_size(void *p) { _sane_allocation_t *sane_alloc = _get_sane_alloc(p); if(sane_alloc != NULL) { - size_t orig_size = sane_alloc->orig_size; + *size = sane_alloc->orig_size; UNLOCK_SANITY_CACHE(); - return orig_size; + return true; } UNLOCK_SANITY_CACHE(); @@ -2891,23 +2955,35 @@ INTERNAL_HIDDEN size_t _iso_chunk_size(void *p) { iso_alloc_zone_t *zone = iso_find_zone_range(p); - if(UNLIKELY(zone == NULL)) { - iso_alloc_big_zone_t *big_zone = iso_find_big_zone(p, false); + if(LIKELY(zone != NULL)) { + /* The chunk size of a zone never changes while it + * holds a live chunk */ + *size = zone->chunk_size; + return true; + } - if(UNLIKELY(big_zone == NULL)) { + iso_alloc_big_zone_t *big_zone = iso_find_big_zone(p, false); + + if(big_zone != NULL) { + *size = big_zone->size; + return true; + } + + return false; +} + +INTERNAL_HIDDEN size_t _iso_chunk_size(void *p) { + size_t size = 0; + + if(UNLIKELY(_iso_alloc_chunk_lookup(p, &size) == false)) { #if ABORT_ON_UNOWNED_PTR - LOG_AND_ABORT("Could not find any zone for allocation at 0x%p", p); + LOG_AND_ABORT("Could not find any zone for allocation at 0x%p", p); #else - return 0; + return 0; #endif - } - - return big_zone->size; } - /* The chunk size of a zone never changes while it holds - * a live chunk */ - return zone->chunk_size; + return size; } INTERNAL_HIDDEN void _free_big_zone_list(iso_alloc_big_zone_t *head) { @@ -2947,6 +3023,78 @@ INTERNAL_HIDDEN void _free_big_zone_list(iso_alloc_big_zone_t *head) { } } +#if THREAD_SUPPORT +/* fork() copies every lock in whatever state the other threads + * left it. A child that inherits a held root mutex or zone flag + * hangs on its first allocation. The prepare handler takes + * every lock in the documented order, root, big zone lists, + * sanity cache, registry, quarantines, zones, so the child + * starts with each one held by the only thread it has, which is + * the one that took them. Both the parent and the child then + * release them. On macOS libSystem calls these through the + * registered malloc zone, elsewhere through pthread_atfork */ +static bool fork_locked; + +INTERNAL_HIDDEN void _iso_alloc_fork_prepare(void) { + if(_root == NULL) { + return; + } + + LOCK_ROOT(); + LOCK_BIG_ZONE_FREE(); + LOCK_BIG_ZONE_USED(); +#if ALLOC_SANITY + LOCK_SANITY_CACHE(); +#endif + LOCK_THREAD_REGISTRY(); + + for(iso_quarantine_t *q = _root->quarantines; q != NULL; q = q->next) { + LOCK_QUARANTINE(q); + } + + const uint16_t zones_used = _root->zones_used; + + for(uint16_t i = 0; i < zones_used; i++) { + LOCK_ZONE(&_root->zones[i]); + } + + fork_locked = true; +} + +static void fork_release(void) { + if(fork_locked == false) { + return; + } + + fork_locked = false; + const uint16_t zones_used = _root->zones_used; + + for(uint16_t i = 0; i < zones_used; i++) { + UNLOCK_ZONE(&_root->zones[i]); + } + + for(iso_quarantine_t *q = _root->quarantines; q != NULL; q = q->next) { + UNLOCK_QUARANTINE(q); + } + + UNLOCK_THREAD_REGISTRY(); +#if ALLOC_SANITY + UNLOCK_SANITY_CACHE(); +#endif + UNLOCK_BIG_ZONE_USED(); + UNLOCK_BIG_ZONE_FREE(); + UNLOCK_ROOT(); +} + +INTERNAL_HIDDEN void _iso_alloc_fork_parent(void) { + fork_release(); +} + +INTERNAL_HIDDEN void _iso_alloc_fork_child(void) { + fork_release(); +} +#endif + INTERNAL_HIDDEN void _iso_alloc_destroy(void) { LOCK_ROOT(); @@ -3006,6 +3154,13 @@ INTERNAL_HIDDEN void _iso_alloc_destroy(void) { munmap((void *) ((uintptr_t) _root->zones - g_page_size), _root->zones_size); #endif +#if ISO_DTOR_CLEANUP + /* Big zones in use belong to the program until it is gone. + * Destructors of other libraries and threads that are still + * running can use them after this one runs, so like the + * zones they are only unmapped when cleanup was asked for. + * The free list is kept too, an allocation after this point + * may reuse an entry from it */ LOCK_BIG_ZONE_USED(); _free_big_zone_list(_root->big_zone_used); UNLOCK_BIG_ZONE_USED(); @@ -3013,6 +3168,7 @@ INTERNAL_HIDDEN void _iso_alloc_destroy(void) { LOCK_BIG_ZONE_FREE(); _free_big_zone_list(_root->big_zone_free); UNLOCK_BIG_ZONE_FREE(); +#endif #if ISO_DTOR_CLEANUP iso_ptr_map_destroy(&_root->zone_map); diff --git a/src/iso_alloc.cpp b/src/iso_alloc.cpp index 61d987d..2a12a17 100644 --- a/src/iso_alloc.cpp +++ b/src/iso_alloc.cpp @@ -66,6 +66,151 @@ static inline void *iso_cpp_new_aligned(size_t size, std::align_val_t val) { return p; } +// On macOS a delete may name a chunk from the system allocator, +// see malloc_hook.c, so the frees go through the hook layer +static inline void iso_cpp_delete(void *p) noexcept { +#if __APPLE__ + _iso_alloc_darwin_free(p); +#else + iso_free(p); +#endif +} + +static inline void iso_cpp_delete_sized(void *p, size_t size) noexcept { +#if __APPLE__ + _iso_alloc_darwin_free_size(p, size); +#else + iso_free_size(p, size); +#endif +} + +// An aligned new rounds the size up to the alignment and may +// use a big zone for alignments above a page, so the sized +// delete has to present the same size, or no size at all +static inline void iso_cpp_delete_sized_aligned(void *p, size_t size, std::align_val_t val) noexcept { + const size_t alignment = static_cast(val); + + if(alignment > g_page_size || alignment == 0) { + iso_cpp_delete(p); + return; + } + + const size_t s = ((size + (alignment - 1)) & ~(alignment - 1)); + + if(s < size) { + iso_cpp_delete(p); + return; + } + + iso_cpp_delete_sized(p, s); +} + +#if __APPLE__ +// With a two level namespace a program's operator new binds +// to libc++ by name, so like malloc the C++ operators are +// taken over by interposing libc++'s symbols. They are named +// here by their mangled names; declaring our own operators +// would define the same symbols and leave nothing to interpose. +// The typed memory operation overloads libc++ added are left +// alone, they call the typed malloc entry points which are +// interposed in malloc_hook.c +extern "C" { +void *_Znwm(size_t); +void *_Znam(size_t); +void *_ZnwmRKSt9nothrow_t(size_t, const std::nothrow_t &); +void *_ZnamRKSt9nothrow_t(size_t, const std::nothrow_t &); +void *_ZnwmSt11align_val_t(size_t, std::align_val_t); +void *_ZnamSt11align_val_t(size_t, std::align_val_t); +void *_ZnwmSt11align_val_tRKSt9nothrow_t(size_t, std::align_val_t, const std::nothrow_t &); +void *_ZnamSt11align_val_tRKSt9nothrow_t(size_t, std::align_val_t, const std::nothrow_t &); +void _ZdlPv(void *); +void _ZdaPv(void *); +void _ZdlPvm(void *, size_t); +void _ZdaPvm(void *, size_t); +void _ZdlPvRKSt9nothrow_t(void *, const std::nothrow_t &); +void _ZdaPvRKSt9nothrow_t(void *, const std::nothrow_t &); +void _ZdlPvSt11align_val_t(void *, std::align_val_t); +void _ZdaPvSt11align_val_t(void *, std::align_val_t); +void _ZdlPvmSt11align_val_t(void *, size_t, std::align_val_t); +void _ZdaPvmSt11align_val_t(void *, size_t, std::align_val_t); +void _ZdlPvSt11align_val_tRKSt9nothrow_t(void *, std::align_val_t, const std::nothrow_t &); +void _ZdaPvSt11align_val_tRKSt9nothrow_t(void *, std::align_val_t, const std::nothrow_t &); +} + +static void *hook_new(size_t size) NEW_EXCEPT { + return iso_cpp_new(size); +} + +static void *hook_new_nothrow(size_t size, const std::nothrow_t &) noexcept { + return iso_alloc(size); +} + +static void *hook_new_aligned(size_t size, std::align_val_t val) NEW_EXCEPT { + return iso_cpp_new_aligned(size, val); +} + +static void *hook_new_aligned_nothrow(size_t size, std::align_val_t val, const std::nothrow_t &) noexcept { + return _iso_alloc_aligned(size, static_cast(val)); +} + +static void hook_delete(void *p) noexcept { + iso_cpp_delete(p); +} + +static void hook_delete_sized(void *p, size_t size) noexcept { + iso_cpp_delete_sized(p, size); +} + +static void hook_delete_nothrow(void *p, const std::nothrow_t &) noexcept { + iso_cpp_delete(p); +} + +static void hook_delete_aligned(void *p, std::align_val_t) noexcept { + iso_cpp_delete(p); +} + +static void hook_delete_sized_aligned(void *p, size_t size, std::align_val_t val) noexcept { + iso_cpp_delete_sized_aligned(p, size, val); +} + +static void hook_delete_aligned_nothrow(void *p, std::align_val_t, const std::nothrow_t &) noexcept { + iso_cpp_delete(p); +} + +typedef void (*iso_interpose_fn_t)(void); + +struct iso_interpose_t { + iso_interpose_fn_t replacement; + iso_interpose_fn_t replacee; +}; + +#define ISO_FN(f) reinterpret_cast(f) + +__attribute__((used)) static const iso_interpose_t iso_cpp_interposers[] __attribute__((section("__DATA,__interpose"))) = { + {ISO_FN(hook_new), ISO_FN(_Znwm)}, + {ISO_FN(hook_new), ISO_FN(_Znam)}, + {ISO_FN(hook_new_nothrow), ISO_FN(_ZnwmRKSt9nothrow_t)}, + {ISO_FN(hook_new_nothrow), ISO_FN(_ZnamRKSt9nothrow_t)}, + {ISO_FN(hook_new_aligned), ISO_FN(_ZnwmSt11align_val_t)}, + {ISO_FN(hook_new_aligned), ISO_FN(_ZnamSt11align_val_t)}, + {ISO_FN(hook_new_aligned_nothrow), ISO_FN(_ZnwmSt11align_val_tRKSt9nothrow_t)}, + {ISO_FN(hook_new_aligned_nothrow), ISO_FN(_ZnamSt11align_val_tRKSt9nothrow_t)}, + {ISO_FN(hook_delete), ISO_FN(_ZdlPv)}, + {ISO_FN(hook_delete), ISO_FN(_ZdaPv)}, + {ISO_FN(hook_delete_sized), ISO_FN(_ZdlPvm)}, + {ISO_FN(hook_delete_sized), ISO_FN(_ZdaPvm)}, + {ISO_FN(hook_delete_nothrow), ISO_FN(_ZdlPvRKSt9nothrow_t)}, + {ISO_FN(hook_delete_nothrow), ISO_FN(_ZdaPvRKSt9nothrow_t)}, + {ISO_FN(hook_delete_aligned), ISO_FN(_ZdlPvSt11align_val_t)}, + {ISO_FN(hook_delete_aligned), ISO_FN(_ZdaPvSt11align_val_t)}, + {ISO_FN(hook_delete_sized_aligned), ISO_FN(_ZdlPvmSt11align_val_t)}, + {ISO_FN(hook_delete_sized_aligned), ISO_FN(_ZdaPvmSt11align_val_t)}, + {ISO_FN(hook_delete_aligned_nothrow), ISO_FN(_ZdlPvSt11align_val_tRKSt9nothrow_t)}, + {ISO_FN(hook_delete_aligned_nothrow), ISO_FN(_ZdaPvSt11align_val_tRKSt9nothrow_t)}, +}; + +#else // !__APPLE__ + // These hooks override the basic new/delete // operators to use the iso_alloc API @@ -74,7 +219,7 @@ EXTERNAL_API FLATTEN void *operator new(size_t size) NEW_EXCEPT { } EXTERNAL_API FLATTEN void operator delete(void *p) noexcept { - iso_free(p); + iso_cpp_delete(p); } EXTERNAL_API FLATTEN void *operator new[](size_t size) NEW_EXCEPT { @@ -82,7 +227,7 @@ EXTERNAL_API FLATTEN void *operator new[](size_t size) NEW_EXCEPT { } EXTERNAL_API FLATTEN void operator delete[](void *p) noexcept { - iso_free(p); + iso_cpp_delete(p); } EXTERNAL_API FLATTEN void *operator new(size_t size, const std::nothrow_t &) noexcept { @@ -93,20 +238,20 @@ EXTERNAL_API FLATTEN void *operator new[](size_t size, const std::nothrow_t &) n return iso_alloc(size); } -FLATTEN void operator delete(void *ptr, size_t size) noexcept { - return iso_free_size(ptr, size); +EXTERNAL_API FLATTEN void operator delete(void *ptr, size_t size) noexcept { + iso_cpp_delete_sized(ptr, size); } -FLATTEN void operator delete[](void *ptr, size_t size) noexcept { - return iso_free_size(ptr, size); +EXTERNAL_API FLATTEN void operator delete[](void *ptr, size_t size) noexcept { + iso_cpp_delete_sized(ptr, size); } EXTERNAL_API FLATTEN void operator delete(void *ptr, const std::nothrow_t &) noexcept { - return iso_free(ptr); + iso_cpp_delete(ptr); } EXTERNAL_API FLATTEN void operator delete[](void *ptr, const std::nothrow_t &) noexcept { - return iso_free(ptr); + iso_cpp_delete(ptr); } EXTERNAL_API FLATTEN void *operator new(size_t size, std::align_val_t val) NEW_EXCEPT { @@ -117,29 +262,41 @@ EXTERNAL_API FLATTEN void *operator new[](size_t size, std::align_val_t val) NEW return iso_cpp_new_aligned(size, val); } -EXTERNAL_API FLATTEN void operator delete(void *p, std::align_val_t val) noexcept { - iso_free(p); +EXTERNAL_API FLATTEN void operator delete(void *p, std::align_val_t) noexcept { + iso_cpp_delete(p); } -EXTERNAL_API FLATTEN void operator delete[](void *p, std::align_val_t val) noexcept { - iso_free(p); +EXTERNAL_API FLATTEN void operator delete[](void *p, std::align_val_t) noexcept { + iso_cpp_delete(p); +} + +EXTERNAL_API FLATTEN void operator delete(void *p, size_t size, std::align_val_t val) noexcept { + iso_cpp_delete_sized_aligned(p, size, val); +} + +EXTERNAL_API FLATTEN void operator delete[](void *p, size_t size, std::align_val_t val) noexcept { + iso_cpp_delete_sized_aligned(p, size, val); } -EXTERNAL_API FLATTEN void *operator new(size_t size, std::align_val_t val, std::nothrow_t &) noexcept { +// The nothrow overloads take a const reference. The previous +// non const declarations mangled differently and never replaced +// the standard library's versions +EXTERNAL_API FLATTEN void *operator new(size_t size, std::align_val_t val, const std::nothrow_t &) noexcept { return _iso_alloc_aligned(size, static_cast(val)); } -EXTERNAL_API FLATTEN void *operator new[](size_t size, std::align_val_t val, std::nothrow_t &) noexcept { +EXTERNAL_API FLATTEN void *operator new[](size_t size, std::align_val_t val, const std::nothrow_t &) noexcept { return _iso_alloc_aligned(size, static_cast(val)); } -EXTERNAL_API FLATTEN void operator delete(void *p, std::align_val_t val, std::nothrow_t &) noexcept { - iso_free(p); +EXTERNAL_API FLATTEN void operator delete(void *p, std::align_val_t, const std::nothrow_t &) noexcept { + iso_cpp_delete(p); } -EXTERNAL_API FLATTEN void operator delete[](void *p, std::align_val_t val, std::nothrow_t &) noexcept { - iso_free(p); +EXTERNAL_API FLATTEN void operator delete[](void *p, std::align_val_t, const std::nothrow_t &) noexcept { + iso_cpp_delete(p); } -#endif -#endif +#endif // __APPLE__ +#endif // MALLOC_HOOK +#endif // CPP_SUPPORT diff --git a/src/iso_alloc_sanity.c b/src/iso_alloc_sanity.c index 90e80cf..2e72ba7 100644 --- a/src/iso_alloc_sanity.c +++ b/src/iso_alloc_sanity.c @@ -174,7 +174,7 @@ INTERNAL_HIDDEN void _verify_zone(iso_alloc_zone_t *zone) { #if USE_SPINLOCK atomic_flag sane_cache_flag; #else -pthread_mutex_t sane_cache_mutex; +pthread_mutex_t sane_cache_mutex = PTHREAD_MUTEX_INITIALIZER; #endif #endif diff --git a/src/malloc_hook.c b/src/malloc_hook.c index 6331709..ff76746 100644 --- a/src/malloc_hook.c +++ b/src/malloc_hook.c @@ -21,6 +21,556 @@ */ #if MALLOC_HOOK +static int hook_posix_memalign(void **r, size_t alignment, size_t size) { + if(r == NULL) { + return EINVAL; + } + + /* POSIX requires a power of 2 that is a multiple of sizeof(void *) */ + if(alignment == 0 || (alignment % sizeof(void *)) != 0 || is_pow2(alignment) == false) { + *r = NULL; + return EINVAL; + } + + *r = _iso_alloc_aligned(size, alignment); + + if(*r != NULL) { + return 0; + } else { + return ENOMEM; + } +} + +static void *hook_memalign(size_t alignment, size_t size) { + if(alignment == 0 || is_pow2(alignment) == false) { + errno = EINVAL; + return NULL; + } + + return _iso_alloc_aligned(size, alignment); +} + +/* Page aligned allocation. The page size is only known once + * the root exists, and valloc may be the first call */ +static void *hook_valloc(size_t size) { + if(UNLIKELY(g_page_size == 0)) { + _iso_alloc_initialize(); + } + + return _iso_alloc_aligned(size, g_page_size); +} + +#if __APPLE__ +/* On macOS the hooks work through dyld interposing and a + * registered malloc zone instead of symbol definitions. + * + * A dylib that merely defines malloc is never called: every + * image is linked with a two level namespace and binds malloc + * to libsystem_malloc by name, and DYLD_FORCE_FLAT_NAMESPACE no + * longer changes that. The __interpose table below asks dyld + * to rebind every image's references to the libSystem symbols + * to our replacements, whether the dylib was inserted with + * DYLD_INSERT_LIBRARIES or linked at build time. References + * made from this dylib are exempt, which is how the + * replacements reach the real libSystem functions. + * + * libSystem allocates before our constructor runs and parts of + * it, CoreFoundation among them, allocate from zones directly, + * so pointers from the system allocator reach free, realloc + * and malloc_size. A pointer libSystem recognizes is handed + * back to the zone that owns it. A pointer no allocator owns + * follows ABORT_ON_UNOWNED_PTR as always. + * + * The zone makes the reverse direction work. libSystem finds + * the owner of a pointer by asking every registered zone, so + * malloc_size, malloc_zone_from_ptr, malloc_zone_free and the + * typed allocation entry points all recognize our chunks. It is + * made zone 0 so malloc_default_zone() allocates from us too, + * and libSystem drives the fork handlers through it. */ +#include +#include +#include + +/* The size of the chunk a request of this size gets, which is + * what malloc_good_size and friends are meant to report */ +static size_t hook_good_size(size_t size) { + if(size < SMALLEST_CHUNK_SZ) { + size = SMALLEST_CHUNK_SZ; + } else if((size % SZ_ALIGNMENT) != 0) { + size = ALIGN_SZ_UP(size); + } + + if(size > SMALL_SIZE_MAX) { + if(UNLIKELY(g_page_size == 0)) { + _iso_alloc_initialize(); + } + + return ROUND_UP_PAGE(size); + } + + return size_class(size); +} + +/* A pointer from another allocator. NULL when no zone owns it */ +static INLINE malloc_zone_t *foreign_zone(const void *p) { + return malloc_zone_from_ptr(p); +} + +INTERNAL_HIDDEN void _iso_alloc_darwin_free(void *p) { + size_t size; + + if(LIKELY(_iso_alloc_chunk_lookup(p, &size) == true)) { + iso_free(p); + return; + } + + malloc_zone_t *zone = foreign_zone(p); + + if(zone != NULL) { + malloc_zone_free(zone, p); + return; + } + +#if ABORT_ON_UNOWNED_PTR + LOG_AND_ABORT("free() of 0x%p which no allocator owns", p); +#endif +} + +INTERNAL_HIDDEN void _iso_alloc_darwin_free_size(void *p, size_t size) { + size_t chunk_size; + + if(LIKELY(_iso_alloc_chunk_lookup(p, &chunk_size) == true)) { + iso_free_size(p, size); + return; + } + + malloc_zone_t *zone = foreign_zone(p); + + if(zone != NULL) { + malloc_zone_free(zone, p); + return; + } + +#if ABORT_ON_UNOWNED_PTR + LOG_AND_ABORT("sized free of 0x%p which no allocator owns", p); +#endif +} + +/* A foreign chunk is migrated into this allocator, which is + * the only way to know its size and release it correctly */ +INTERNAL_HIDDEN void *_iso_alloc_darwin_realloc(void *p, size_t size) { + size_t chunk_size; + + if(LIKELY(_iso_alloc_chunk_lookup(p, &chunk_size) == true)) { + return iso_realloc(p, size); + } + + malloc_zone_t *zone = foreign_zone(p); + + if(zone == NULL) { +#if ABORT_ON_UNOWNED_PTR + LOG_AND_ABORT("realloc() of 0x%p which no allocator owns", p); +#else + errno = EINVAL; + return NULL; +#endif + } + + if(size == 0) { + malloc_zone_free(zone, p); + return NULL; + } + + const size_t old_size = zone->size(zone, p); + void *r = iso_alloc(size); + + if(r == NULL) { + return NULL; + } + + memcpy(r, p, (old_size < size) ? old_size : size); + malloc_zone_free(zone, p); + return r; +} + +static void *hook_malloc(size_t size) { + return iso_alloc(size); +} + +static void *hook_calloc(size_t nmemb, size_t size) { + return iso_calloc(nmemb, size); +} + +static void hook_free(void *p) { + _iso_alloc_darwin_free(p); +} + +static void *hook_realloc(void *p, size_t size) { + return _iso_alloc_darwin_realloc(p, size); +} + +static void *hook_reallocf(void *p, size_t size) { + void *r = _iso_alloc_darwin_realloc(p, size); + + if(r == NULL && size != 0) { + _iso_alloc_darwin_free(p); + } + + return r; +} + +static size_t hook_malloc_size(const void *p) { + size_t size; + + if(LIKELY(_iso_alloc_chunk_lookup((void *) p, &size) == true)) { + return size; + } + + malloc_zone_t *zone = foreign_zone(p); + + if(zone != NULL) { + return zone->size(zone, p); + } + + return 0; +} + +#if defined(__MAC_14_0) && __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_14_0 +/* Typed memory operations. Code built with them, which includes + * the system frameworks, calls these instead of malloc. The + * type id is a hint for the system allocator's own isolation + * scheme; our size classes already isolate by size */ +#define ISO_TYPED_HOOKS 1 + +static void *hook_type_malloc(size_t size, malloc_type_id_t type_id) { + (void) type_id; + return iso_alloc(size); +} + +static void *hook_type_calloc(size_t nmemb, size_t size, malloc_type_id_t type_id) { + (void) type_id; + return iso_calloc(nmemb, size); +} + +static void hook_type_free(void *p, malloc_type_id_t type_id) { + (void) type_id; + _iso_alloc_darwin_free(p); +} + +static void *hook_type_realloc(void *p, size_t size, malloc_type_id_t type_id) { + (void) type_id; + return _iso_alloc_darwin_realloc(p, size); +} + +static void *hook_type_valloc(size_t size, malloc_type_id_t type_id) { + (void) type_id; + return hook_valloc(size); +} + +static void *hook_type_aligned_alloc(size_t alignment, size_t size, malloc_type_id_t type_id) { + (void) type_id; + return hook_memalign(alignment, size); +} + +static int hook_type_posix_memalign(void **r, size_t alignment, size_t size, malloc_type_id_t type_id) { + (void) type_id; + return hook_posix_memalign(r, alignment, size); +} +#endif + +/* The malloc zone. libSystem consults size() on every zone to + * find the owner of a pointer so it has to be fast for a + * negative answer, which the zone map probe is */ +static size_t zone_size(malloc_zone_t *zone, const void *p) { + (void) zone; + size_t size; + + if(_iso_alloc_chunk_lookup((void *) p, &size) == false) { + return 0; + } + + return size; +} + +static void *zone_malloc(malloc_zone_t *zone, size_t size) { + (void) zone; + return iso_alloc(size); +} + +static void *zone_calloc(malloc_zone_t *zone, size_t nmemb, size_t size) { + (void) zone; + return iso_calloc(nmemb, size); +} + +static void *zone_valloc(malloc_zone_t *zone, size_t size) { + (void) zone; + return hook_valloc(size); +} + +static void zone_free(malloc_zone_t *zone, void *p) { + (void) zone; + _iso_alloc_darwin_free(p); +} + +static void *zone_realloc(malloc_zone_t *zone, void *p, size_t size) { + (void) zone; + return _iso_alloc_darwin_realloc(p, size); +} + +static void zone_destroy(malloc_zone_t *zone) { + /* The zone lives as long as the process */ + (void) zone; +} + +static unsigned zone_batch_malloc(malloc_zone_t *zone, size_t size, void **results, unsigned count) { + (void) zone; + unsigned i; + + for(i = 0; i < count; i++) { + results[i] = iso_alloc(size); + + if(results[i] == NULL) { + break; + } + } + + return i; +} + +static void zone_batch_free(malloc_zone_t *zone, void **to_be_freed, unsigned count) { + (void) zone; + + for(unsigned i = 0; i < count; i++) { + _iso_alloc_darwin_free(to_be_freed[i]); + to_be_freed[i] = NULL; + } +} + +static void *zone_memalign(malloc_zone_t *zone, size_t alignment, size_t size) { + (void) zone; + return hook_memalign(alignment, size); +} + +static void zone_free_definite_size(malloc_zone_t *zone, void *p, size_t size) { + /* The caller's idea of the size is not trusted over our own + * lookup, which the unsized free performs anyway */ + (void) zone; + (void) size; + _iso_alloc_darwin_free(p); +} + +static size_t zone_pressure_relief(malloc_zone_t *zone, size_t goal) { + (void) zone; + (void) goal; + return 0; +} + +static boolean_t zone_claimed_address(malloc_zone_t *zone, void *p) { + (void) zone; + size_t size; + return _iso_alloc_chunk_lookup(p, &size); +} + +static kern_return_t intro_enumerator(task_t task, void *context, unsigned type_mask, vm_address_t zone_address, + memory_reader_t reader, vm_range_recorder_t recorder) { + (void) task; + (void) context; + (void) type_mask; + (void) zone_address; + (void) reader; + (void) recorder; + return KERN_SUCCESS; +} + +static size_t intro_good_size(malloc_zone_t *zone, size_t size) { + (void) zone; + return hook_good_size(size); +} + +static boolean_t intro_check(malloc_zone_t *zone) { + (void) zone; + return 1; +} + +static void intro_print(malloc_zone_t *zone, boolean_t verbose) { + (void) zone; + (void) verbose; +} + +static void intro_log(malloc_zone_t *zone, void *address) { + (void) zone; + (void) address; +} + +/* libSystem calls these from its own fork handlers, which is + * how the allocator state is quiesced across fork() on macOS. + * reinit_lock runs in the child before anything else in + * libSystem allocates and must not be NULL at version >= 9 */ +static void intro_force_lock(malloc_zone_t *zone) { + (void) zone; +#if THREAD_SUPPORT + _iso_alloc_fork_prepare(); +#endif +} + +static void intro_force_unlock(malloc_zone_t *zone) { + (void) zone; +#if THREAD_SUPPORT + _iso_alloc_fork_parent(); +#endif +} + +static void intro_reinit_lock(malloc_zone_t *zone) { + (void) zone; +#if THREAD_SUPPORT + _iso_alloc_fork_child(); +#endif +} + +static void intro_statistics(malloc_zone_t *zone, malloc_statistics_t *stats) { + (void) zone; + stats->blocks_in_use = 0; + stats->size_in_use = 0; + stats->max_size_in_use = 0; + stats->size_allocated = 0; +} + +static boolean_t intro_zone_locked(malloc_zone_t *zone) { + (void) zone; + return 0; +} + +static boolean_t intro_enable_discharge_checking(malloc_zone_t *zone) { + (void) zone; + return 0; +} + +static void intro_disable_discharge_checking(malloc_zone_t *zone) { + (void) zone; +} + +static void intro_discharge(malloc_zone_t *zone, void *memory) { + (void) zone; + (void) memory; +} + +static malloc_introspection_t iso_zone_introspect = { + .enumerator = intro_enumerator, + .good_size = intro_good_size, + .check = intro_check, + .print = intro_print, + .log = intro_log, + .force_lock = intro_force_lock, + .force_unlock = intro_force_unlock, + .statistics = intro_statistics, + .zone_locked = intro_zone_locked, + .enable_discharge_checking = intro_enable_discharge_checking, + .disable_discharge_checking = intro_disable_discharge_checking, + .discharge = intro_discharge, + .enumerate_discharged_pointers = NULL, + .reinit_lock = intro_reinit_lock, +}; + +/* Version 10 is the newest layout whose members are all + * optional or provided here. Newer versions add typed and + * flagged entry points that libSystem routes to malloc and + * memalign when the zone is older */ +static malloc_zone_t iso_malloc_zone = { + .reserved1 = NULL, + .reserved2 = NULL, + .size = zone_size, + .malloc = zone_malloc, + .calloc = zone_calloc, + .valloc = zone_valloc, + .free = zone_free, + .realloc = zone_realloc, + .destroy = zone_destroy, + .zone_name = "isoalloc", + .batch_malloc = zone_batch_malloc, + .batch_free = zone_batch_free, + .introspect = &iso_zone_introspect, + .version = 10, + .memalign = zone_memalign, + .free_definite_size = zone_free_definite_size, + .pressure_relief = zone_pressure_relief, + .claimed_address = zone_claimed_address, +}; + +/* Registers the zone and makes it zone 0, the one + * malloc_default_zone() forwards to. Runs once after the root + * exists and outside the root lock, see post_root_init. + * + * malloc_zone_unregister moves the last registered zone into + * the freed slot, so registering ours and then unregistering + * and re-registering the old zone 0 swaps the two. The old + * default keeps serving the pointers it already handed out. + * The purgeable zone is created first so it is built on the + * system zone, and re-registered so it stays behind us */ +INTERNAL_HIDDEN void _iso_alloc_darwin_zone_init(void) { + malloc_zone_t *purgeable = malloc_default_purgeable_zone(); + malloc_zone_t **zones = NULL; + unsigned count = 0; + malloc_zone_t *system_zone = NULL; + + if(malloc_get_all_zones(0, NULL, (vm_address_t **) &zones, &count) == KERN_SUCCESS && count > 0) { + system_zone = zones[0]; + } + + malloc_zone_register(&iso_malloc_zone); + + if(system_zone != NULL && system_zone != &iso_malloc_zone) { + malloc_zone_unregister(system_zone); + malloc_zone_register(system_zone); + } + + if(purgeable != NULL && purgeable != system_zone) { + malloc_zone_unregister(purgeable); + malloc_zone_register(purgeable); + } +} + +/* libSystem has no memalign, so this one is a plain export + * for programs that link the library and call it */ +EXTERNAL_API void *memalign(size_t alignment, size_t size) { + return hook_memalign(alignment, size); +} + +/* The interpose table dyld reads at load time. Function + * pointers are stored as a generic function type so the + * entries are valid in pedantic C; dyld only wants addresses */ +typedef void (*iso_interpose_fn_t)(void); + +typedef struct { + iso_interpose_fn_t replacement; + iso_interpose_fn_t replacee; +} iso_interpose_t; + +#define ISO_INTERPOSE(hook, orig) { (iso_interpose_fn_t) hook, (iso_interpose_fn_t) orig } + +__attribute__((used)) static const iso_interpose_t iso_interposers[] __attribute__((section("__DATA,__interpose"))) = { + ISO_INTERPOSE(hook_malloc, malloc), + ISO_INTERPOSE(hook_calloc, calloc), + ISO_INTERPOSE(hook_realloc, realloc), + ISO_INTERPOSE(hook_reallocf, reallocf), + ISO_INTERPOSE(hook_free, free), + ISO_INTERPOSE(hook_posix_memalign, posix_memalign), + ISO_INTERPOSE(hook_memalign, aligned_alloc), + ISO_INTERPOSE(hook_valloc, valloc), + ISO_INTERPOSE(hook_malloc_size, malloc_size), + ISO_INTERPOSE(hook_good_size, malloc_good_size), +#if ISO_TYPED_HOOKS + ISO_INTERPOSE(hook_type_malloc, malloc_type_malloc), + ISO_INTERPOSE(hook_type_calloc, malloc_type_calloc), + ISO_INTERPOSE(hook_type_free, malloc_type_free), + ISO_INTERPOSE(hook_type_realloc, malloc_type_realloc), + ISO_INTERPOSE(hook_type_valloc, malloc_type_valloc), + ISO_INTERPOSE(hook_type_aligned_alloc, malloc_type_aligned_alloc), + ISO_INTERPOSE(hook_type_posix_memalign, malloc_type_posix_memalign), +#endif +}; + +#else /* !__APPLE__ */ + /* malloc/free/calloc/realloc and their __libc_ variants are * direct linker aliases for the iso_ equivalents on GCC >= 9 * and Clang >= 10 (see iso_alloc_hook.h). This propagates all @@ -29,7 +579,7 @@ * eliminates the wrapper call entirely. * * Functions with differing signatures or custom logic (posix_memalign, - * aligned_alloc, memalign, malloc_size, malloc_good_size) remain + * aligned_alloc, memalign, valloc, malloc_usable_size) remain * as wrapper functions. */ EXTERNAL_API void *__libc_malloc(size_t s) ISO_FORWARD1(iso_alloc, s) @@ -47,82 +597,51 @@ EXTERNAL_API void *realloc(void *p, size_t s) ISO_FORWARD2(iso_realloc, p, s) EXTERNAL_API void *__libc_reallocarray(void *p, size_t n, size_t s) ISO_FORWARD3(iso_reallocarray, p, n, s) EXTERNAL_API void *reallocarray(void *p, size_t n, size_t s) ISO_FORWARD3(iso_reallocarray, p, n, s) -EXTERNAL_API int __posix_memalign(void **r, size_t a, size_t s) { - if(r == NULL) { - return EINVAL; - } - - /* POSIX requires a power of 2 that is a multiple of sizeof(void *) */ - if(a == 0 || (a % sizeof(void *)) != 0 || is_pow2(a) == false) { - *r = NULL; - return EINVAL; - } - - *r = _iso_alloc_aligned(s, a); - - if(*r != NULL) { - return 0; - } else { - return ENOMEM; - } +EXTERNAL_API int __posix_memalign(void **r, size_t alignment, size_t s) { + return hook_posix_memalign(r, alignment, s); } EXTERNAL_API int posix_memalign(void **r, size_t alignment, size_t s) { - return __posix_memalign(r, alignment, s); + return hook_posix_memalign(r, alignment, s); } EXTERNAL_API void *memalign(size_t alignment, size_t s) { - if(alignment == 0 || is_pow2(alignment) == false) { - errno = EINVAL; - return NULL; - } - - return _iso_alloc_aligned(s, alignment); + return hook_memalign(alignment, s); } EXTERNAL_API void *__libc_memalign(size_t alignment, size_t s) { - return memalign(alignment, s); + return hook_memalign(alignment, s); } EXTERNAL_API void *aligned_alloc(size_t alignment, size_t s) { - return memalign(alignment, s); + return hook_memalign(alignment, s); } -#if __ANDROID__ || __FreeBSD__ -EXTERNAL_API size_t malloc_usable_size(const void *ptr) { - return iso_chunksz((void *) ptr); +/* Without these a program gets the libc versions and the + * chunks they return reach free() as pointers we do not own */ +EXTERNAL_API void *valloc(size_t s) { + return hook_valloc(s); } -#elif __APPLE__ -EXTERNAL_API size_t malloc_size(const void *ptr) { - return iso_chunksz((void *) ptr); + +#if __linux__ +EXTERNAL_API void *pvalloc(size_t s) { + if(UNLIKELY(g_page_size == 0)) { + _iso_alloc_initialize(); + } + + return _iso_alloc_aligned(ROUND_UP_PAGE(s), g_page_size); } +#endif -EXTERNAL_API size_t malloc_good_size(size_t size) { - return ALIGN_SZ_UP(size); +#if __ANDROID__ || __FreeBSD__ +EXTERNAL_API size_t malloc_usable_size(const void *ptr) { + return iso_chunksz((void *) ptr); } #else /* On Linux (non-Android) malloc_usable_size takes void* matching iso_chunksz */ EXTERNAL_API size_t malloc_usable_size(void *ptr) ISO_FORWARD1(iso_chunksz, ptr) #endif -static void *libc_malloc(size_t s, const void *caller) { - return iso_alloc(s); -} -static void *libc_realloc(void *ptr, size_t s, const void *caller) { - return iso_realloc(ptr, s); -} -static void libc_free(void *ptr, const void *caller) { - iso_free(ptr); -} -static void *libc_memalign(size_t alignment, size_t s, const void *caller) { - return iso_alloc(s); -} - -#if !__ANDROID__ -void *(*__malloc_hook)(size_t, const void *) = &libc_malloc; -void *(*__realloc_hook)(void *, size_t, const void *) = &libc_realloc; -void (*__free_hook)(void *, const void *) = &libc_free; -void *(*__memalign_hook)(size_t, size_t, const void *) = &libc_memalign; -#endif -#endif +#endif /* __APPLE__ */ +#endif /* MALLOC_HOOK */ // clang-format on diff --git a/tests/preload/cpp_hooks.cpp b/tests/preload/cpp_hooks.cpp new file mode 100644 index 0000000..a7cfb99 --- /dev/null +++ b/tests/preload/cpp_hooks.cpp @@ -0,0 +1,151 @@ +// cpp_hooks.cpp - Every operator new and delete must reach +// IsoAlloc when the library is preloaded +// Copyright 2023 - chris.rohlf@gmail.com + +#include "preload_test.h" +#include +#include +#include +#include +#include +#include +#include +#include + +struct Big { + std::vector v; + Big() : v(1 << 20, 'x') {} + ~Big() { + // Runs from the exit handlers after main returns + v[0] = 'y'; + } +}; + +static Big g_big; +static void *volatile g_sink; + +thread_local std::string tls_str = "a thread local string long enough to live on the heap"; + +struct alignas(64) A64 { + char c[200]; +}; + +struct alignas(16384) APage { + char c[100]; +}; + +int main() { + preload_resolve(); + + // The program binds operator new to the standard library, + // interposing must redirect that binding +#ifdef __APPLE__ + Dl_info info; + void *op = reinterpret_cast(static_cast(&::operator new)); + + if(dladdr(op, &info) == 0 || info.dli_fname == NULL || strstr(info.dli_fname, "isoalloc") == NULL) { + FAIL("operator new is bound to %s", info.dli_fname ? info.dli_fname : "?"); + } +#endif + + char *p = new char[300]; + size_t sz = expect_owned(p, 300, "new char[300]"); + + if(sz != 320) { + FAIL("new char[300] chunk size is %zu, expected 320", sz); + } + + delete[] p; + + auto *s = new std::string(500, 'q'); + expect_owned(s, sizeof(std::string), "new std::string"); + delete s; + + auto *n = new(std::nothrow) char[400]; + expect_owned(n, 400, "new(nothrow) char[400]"); + delete[] n; + + auto *a = new A64; + expect_owned(a, sizeof(A64), "new A64"); + expect_aligned(a, 64, "new A64"); + delete a; + + auto *aa = new A64[8]; + expect_aligned(aa, 64, "new A64[8]"); + delete[] aa; + + auto *an = new(std::nothrow) A64; + expect_owned(an, sizeof(A64), "new(nothrow) A64"); + expect_aligned(an, 64, "new(nothrow) A64"); + delete an; + + // Above a page the aligned new uses a big zone and the sized + // aligned delete has to cope with that + auto *pg = new APage; + expect_owned(pg, sizeof(APage), "new APage"); + expect_aligned(pg, 16384, "new APage"); + delete pg; + + auto *pga = new APage[2]; + expect_aligned(pga, 16384, "new APage[2]"); + delete[] pga; + + // Containers, threads and thread locals + std::map m; + + for(int i = 0; i < 10000; i++) { + m[i] = std::string(i % 500, 'z'); + } + + // A library built without THREAD_SUPPORT is only meant for + // single threaded programs, the runner tells us to skip + const int thread_count = getenv("ISO_PRELOAD_NO_THREADS") != nullptr ? 0 : 8; + std::vector ts; + + for(int i = 0; i < thread_count; i++) { + ts.emplace_back([i]() { + tls_str += std::to_string(i); + std::vector v; + + for(int j = 0; j < 1000; j++) { + v.emplace_back(j % 300, 'a'); + } + }); + } + + for(auto &t : ts) { + t.join(); + } + + auto sp = std::make_shared>(100000, 7); + + if((*sp)[99999] != 7) { + FAIL("shared vector contents wrong"); + } + + // A throwing new must throw, a nothrow new must return NULL. + // The pointer escapes through a volatile so the compiler can + // not elide the allocation, which C++14 allows for an unused new + bool threw = false; + volatile size_t huge = (size_t) 1 << 62; + + try { + g_sink = new char[huge]; + delete[] static_cast(g_sink); + } catch(const std::bad_alloc &) { + threw = true; + } + + if(threw == false) { + FAIL("new did not throw bad_alloc for an impossible size"); + } + + g_sink = new(std::nothrow) char[huge]; + + if(g_sink != nullptr) { + FAIL("nothrow new returned memory for an impossible size"); + } + + std::cout << "cpp_hooks ok " << m.size() << std::endl; + return 0; +} diff --git a/tests/preload/exit_order_lib.c b/tests/preload/exit_order_lib.c new file mode 100644 index 0000000..6739fe1 --- /dev/null +++ b/tests/preload/exit_order_lib.c @@ -0,0 +1,49 @@ +/* exit_order_lib.c - A library the test program depends on. + * On Linux its destructor runs after the preloaded allocator's + * destructor, so the allocator must leave memory mapped + * Copyright 2023 - chris.rohlf@gmail.com */ + +#include +#include +#include +#include + +#define BIG (1 << 20) + +static char *small; +static char *big; + +__attribute__((constructor)) static void exit_order_ctor(void) { + small = malloc(100); + big = malloc(BIG); + memset(small, 1, 100); + memset(big, 1, BIG); +} + +__attribute__((destructor)) static void exit_order_dtor(void) { + /* Touch, free and allocate again, which a destructor of + * any library is entitled to do */ + if(small[99] != 1 || big[0] != 1 || big[BIG - 1] != 1) { + fprintf(stderr, "FAIL exit_order: memory changed under a live allocation\n"); + _exit(1); + } + + big[0] = 2; + free(big); + free(small); + char *x = malloc(BIG); + + if(x == NULL) { + fprintf(stderr, "FAIL exit_order: malloc failed in a destructor\n"); + _exit(1); + } + + memset(x, 3, BIG); + free(x); + fprintf(stderr, "exit_order ok\n"); +} + +void exit_order_touch(void) { + small[0] = 5; + big[100] = 5; +} diff --git a/tests/preload/exit_order_main.c b/tests/preload/exit_order_main.c new file mode 100644 index 0000000..27014d8 --- /dev/null +++ b/tests/preload/exit_order_main.c @@ -0,0 +1,16 @@ +/* exit_order_main.c - Runs the destructor of exit_order_lib + * after the allocator's own destructor + * Copyright 2023 - chris.rohlf@gmail.com */ + +#include "preload_test.h" + +void exit_order_touch(void); + +int main(void) { + preload_resolve(); + exit_order_touch(); + void *p = malloc(1 << 20); + expect_owned(p, 1 << 20, "malloc(1 MB)"); + /* Deliberately leaked so a big zone is in use at exit */ + return 0; +} diff --git a/tests/preload/foreign_ptr.c b/tests/preload/foreign_ptr.c new file mode 100644 index 0000000..d48bb5d --- /dev/null +++ b/tests/preload/foreign_ptr.c @@ -0,0 +1,137 @@ +/* foreign_ptr.c - Pointers from the system allocator must + * survive free, realloc and malloc_size through the hooks + * Copyright 2023 - chris.rohlf@gmail.com + * + * On macOS libSystem allocates before the constructor runs and + * frameworks allocate from their own zones, so these pointers + * reach the interposed functions in every real program */ + +#include "preload_test.h" + +#ifdef __APPLE__ +#include + +/* The system zone that was zone 0 before IsoAlloc took over */ +static malloc_zone_t *system_zone(void) { + vm_address_t *zones = NULL; + unsigned count = 0; + + if(malloc_get_all_zones(0, NULL, &zones, &count) != KERN_SUCCESS) { + FAIL("malloc_get_all_zones failed"); + } + + for(unsigned i = 0; i < count; i++) { + malloc_zone_t *z = (malloc_zone_t *) zones[i]; + + if(z->zone_name != NULL && strcmp(z->zone_name, "DefaultMallocZone") == 0) { + return z; + } + } + + FAIL("no system zone found among %u zones", count); +} + +int main(void) { + preload_resolve(); + malloc_zone_t *sys = system_zone(); + const char *text = "hello from the system allocator"; + + /* realloc of a foreign pointer keeps its contents and + * migrates it into IsoAlloc */ + char *f = malloc_zone_malloc(sys, 64); + + if(f == NULL) { + FAIL("system zone malloc failed"); + } + + strcpy(f, text); + + if(malloc_size(f) < 64) { + FAIL("malloc_size of a foreign pointer is %zu", malloc_size(f)); + } + + char *r = realloc(f, 4096); + expect_owned(r, 4096, "realloc(foreign, 4096)"); + + if(strcmp(r, text) != 0) { + FAIL("realloc of a foreign pointer lost the contents: '%s'", r); + } + + free(r); + + /* realloc to zero frees it */ + f = malloc_zone_malloc(sys, 64); + + if(realloc(f, 0) != NULL) { + FAIL("realloc(foreign, 0) did not return NULL"); + } + + /* free of a foreign pointer returns it to its zone */ + for(int i = 0; i < 1000; i++) { + f = malloc_zone_malloc(sys, 100 + i); + memset(f, 1, 100 + i); + free(f); + } + + f = malloc_zone_calloc(sys, 16, 16); + free(f); + f = malloc_zone_valloc(sys, 100); + free(f); + + /* reallocf of a foreign pointer */ + f = malloc_zone_malloc(sys, 32); + strcpy(f, "reallocf"); + r = reallocf(f, 1000); + expect_owned(r, 1000, "reallocf(foreign, 1000)"); + + if(strcmp(r, "reallocf") != 0) { + FAIL("reallocf lost the contents"); + } + + free(r); + + /* Our chunks through the zone API of the system zone's + * pointer are not valid, but through the default zone and + * malloc_zone_from_ptr they are */ + char *p = malloc(100); + malloc_zone_t *owner = malloc_zone_from_ptr(p); + + if(owner == NULL) { + FAIL("malloc_zone_from_ptr did not find our chunk"); + } + + if(malloc_zone_from_ptr(malloc_zone_malloc(sys, 8)) != sys) { + FAIL("malloc_zone_from_ptr does not find the system zone's chunk"); + } + + malloc_zone_free(owner, p); + + /* A mix of both allocators in one data structure */ + char *mixed[64]; + + for(int i = 0; i < 64; i++) { + mixed[i] = (i & 1) ? malloc(50) : malloc_zone_malloc(sys, 50); + memset(mixed[i], i, 50); + } + + for(int i = 0; i < 64; i++) { + mixed[i] = realloc(mixed[i], 500); + + if(mixed[i][49] != (char) i) { + FAIL("mixed realloc lost contents at %d", i); + } + } + + for(int i = 0; i < 64; i++) { + free(mixed[i]); + } + + printf("foreign_ptr ok\n"); + return 0; +} +#else +int main(void) { + printf("foreign_ptr skipped, only meaningful on macOS\n"); + return 0; +} +#endif diff --git a/tests/preload/fork_safety.c b/tests/preload/fork_safety.c new file mode 100644 index 0000000..e189d13 --- /dev/null +++ b/tests/preload/fork_safety.c @@ -0,0 +1,114 @@ +/* fork_safety.c - A child forked while other threads allocate + * must be able to allocate itself + * Copyright 2023 - chris.rohlf@gmail.com */ + +#include "preload_test.h" +#include +#include +#include +#include + +#define THREADS 6 +#define CHILD_WAIT_MS 5000 + +static volatile int stop; + +static void *churn(void *arg) { + size_t base = 16 + ((size_t) arg * 48); + void *p[64]; + + while(stop == 0) { + for(int i = 0; i < 64; i++) { + p[i] = malloc(base + (i % 8) * 16); + } + + for(int i = 0; i < 64; i++) { + free(p[i]); + } + } + + return NULL; +} + +int main(int argc, char **argv) { + int iterations = (argc > 1) ? atoi(argv[1]) : 100; + pthread_t t[THREADS]; + preload_resolve(); + + for(long i = 0; i < THREADS; i++) { + pthread_create(&t[i], NULL, churn, (void *) i); + } + + int hung = 0; + int bad = 0; + + for(int i = 0; i < iterations; i++) { + pid_t pid = fork(); + + if(pid == 0) { + /* Every size class the parents threads were using, + * plus one that needs a new zone and a big one */ + for(int j = 0; j < 2000; j++) { + void *p = malloc(16 + (j % 400)); + + if(p == NULL) { + _exit(2); + } + + free(p); + } + + void *n = malloc(7000); + void *big = malloc(1 << 20); + + if(n == NULL || big == NULL) { + _exit(3); + } + + free(n); + free(big); + _exit(0); + } + + if(pid < 0) { + FAIL("fork failed"); + } + + int status = 0; + int waited = 0; + + for(;;) { + pid_t r = waitpid(pid, &status, WNOHANG); + + if(r == pid) { + break; + } + + usleep(1000); + + if(++waited > CHILD_WAIT_MS) { + kill(pid, SIGKILL); + waitpid(pid, &status, 0); + hung++; + break; + } + } + + if(waited <= CHILD_WAIT_MS && (!WIFEXITED(status) || WEXITSTATUS(status) != 0)) { + bad++; + } + } + + stop = 1; + + for(int i = 0; i < THREADS; i++) { + pthread_join(t[i], NULL); + } + + if(hung != 0 || bad != 0) { + FAIL("%d children hung and %d crashed out of %d forks", hung, bad, iterations); + } + + printf("fork_safety ok, %d children\n", iterations); + return 0; +} diff --git a/tests/preload/interpose_check.c b/tests/preload/interpose_check.c new file mode 100644 index 0000000..7f87c79 --- /dev/null +++ b/tests/preload/interpose_check.c @@ -0,0 +1,255 @@ +/* interpose_check.c - Every libc allocation entry point must + * reach IsoAlloc when the library is preloaded + * Copyright 2023 - chris.rohlf@gmail.com */ + +#include "preload_test.h" +#include +#include + +#ifdef __APPLE__ +#include +#include +#else +#include +#endif + +int main(void) { + preload_resolve(); + + /* A 300 byte request lands in the 320 byte size class. The + * exact value proves the chunk came from IsoAlloc rather + * than a system allocator that happens to round similarly */ + char *p = malloc(300); + size_t sz = expect_owned(p, 300, "malloc(300)"); + + if(sz != 320) { + FAIL("malloc(300) chunk size is %zu, expected the 320 byte class", sz); + } + + memset(p, 'a', 300); + +#ifdef __APPLE__ + if(malloc_size(p) != sz) { + FAIL("malloc_size(%p) = %zu but iso_chunksz says %zu", (void *) p, malloc_size(p), sz); + } + + if(malloc_good_size(300) < 300 || malloc_good_size(300) != sz) { + FAIL("malloc_good_size(300) = %zu, expected %zu", malloc_good_size(300), sz); + } + + /* The program's own binding, not just the pointer */ + Dl_info info; + + if(dladdr((void *) &malloc, &info) == 0 || info.dli_fname == NULL || strstr(info.dli_fname, "isoalloc") == NULL) { + FAIL("malloc is bound to %s, interposing did not take effect", info.dli_fname ? info.dli_fname : "?"); + } + + if(dladdr((void *) &free, &info) == 0 || info.dli_fname == NULL || strstr(info.dli_fname, "isoalloc") == NULL) { + FAIL("free is bound to %s, interposing did not take effect", info.dli_fname ? info.dli_fname : "?"); + } +#else + if(malloc_usable_size(p) != sz) { + FAIL("malloc_usable_size(%p) = %zu but iso_chunksz says %zu", (void *) p, malloc_usable_size(p), sz); + } +#endif + + /* realloc keeps contents and stays in IsoAlloc */ + p = realloc(p, 5000); + expect_owned(p, 5000, "realloc(p, 5000)"); + + for(int i = 0; i < 300; i++) { + if(p[i] != 'a') { + FAIL("realloc lost the contents at offset %d", i); + } + } + + free(p); + + char *q = realloc(NULL, 64); + expect_owned(q, 64, "realloc(NULL, 64)"); + free(q); + + /* calloc is zeroed, including a chunk that was used before */ + for(int round = 0; round < 2; round++) { + uint8_t *c = calloc(10, 30); + expect_owned(c, 300, "calloc(10, 30)"); + + for(int i = 0; i < 300; i++) { + if(c[i] != 0) { + FAIL("calloc returned non zero memory at offset %d", i); + } + } + + memset(c, 0xff, 300); + free(c); + } + + /* Zero sized requests must not be NULL, programs treat + * that as out of memory. This was broken whenever the + * root was created before the constructor ran */ + void *z = malloc(0); + + if(z == NULL) { + FAIL("malloc(0) returned NULL"); + } + + free(z); + z = calloc(0, 16); + + if(z == NULL) { + FAIL("calloc(0, 16) returned NULL"); + } + + free(z); + free(NULL); + + /* Aligned allocations */ + void *a = NULL; + int r = posix_memalign(&a, 4096, 100); + + if(r != 0) { + FAIL("posix_memalign returned %d", r); + } + + expect_owned(a, 100, "posix_memalign(4096, 100)"); + expect_aligned(a, 4096, "posix_memalign(4096, 100)"); + free(a); + + if(posix_memalign(&a, 3, 100) != EINVAL) { + FAIL("posix_memalign accepted a bad alignment"); + } + + a = aligned_alloc(256, 512); + expect_owned(a, 512, "aligned_alloc(256, 512)"); + expect_aligned(a, 256, "aligned_alloc(256, 512)"); + free(a); + + long page = sysconf(_SC_PAGESIZE); + a = valloc(100); + expect_owned(a, 100, "valloc(100)"); + expect_aligned(a, (size_t) page, "valloc(100)"); + free(a); + +#if defined(__GLIBC__) + a = pvalloc(100); + expect_owned(a, (size_t) page, "pvalloc(100)"); + expect_aligned(a, (size_t) page, "pvalloc(100)"); + free(a); + + a = memalign(1024, 100); + expect_owned(a, 100, "memalign(1024, 100)"); + expect_aligned(a, 1024, "memalign(1024, 100)"); + free(a); +#endif + + /* libc functions that allocate internally */ + char *s = strdup("a string that is long enough to not be in the smallest class"); + expect_owned(s, strlen(s) + 1, "strdup"); + free(s); + s = strndup("abcdef", 3); + expect_owned(s, 4, "strndup"); + + if(strcmp(s, "abc") != 0) { + FAIL("strndup returned '%s'", s); + } + + free(s); + + /* A big allocation */ + char *big = malloc(1 << 20); + expect_owned(big, 1 << 20, "malloc(1 MB)"); + memset(big, 1, 1 << 20); + big = realloc(big, 1 << 21); + expect_owned(big, 1 << 21, "realloc(1 MB -> 2 MB)"); + + if(big[0] != 1 || big[(1 << 20) - 1] != 1) { + FAIL("realloc of a big allocation lost the contents"); + } + + free(big); + +#ifdef __APPLE__ + /* The zone must be zone 0, so that libSystem routes + * malloc_default_zone() and the typed allocation entry + * points to IsoAlloc, and must know our pointers */ + vm_address_t *zones = NULL; + unsigned count = 0; + + if(malloc_get_all_zones(0, NULL, &zones, &count) != KERN_SUCCESS || count == 0) { + FAIL("malloc_get_all_zones failed"); + } + + malloc_zone_t *zone0 = (malloc_zone_t *) zones[0]; + + if(zone0->zone_name == NULL || strcmp(zone0->zone_name, "isoalloc") != 0) { + FAIL("zone 0 is '%s', expected isoalloc", zone0->zone_name ? zone0->zone_name : "(null)"); + } + + char *zp = malloc_zone_malloc(malloc_default_zone(), 100); + expect_owned(zp, 100, "malloc_zone_malloc(malloc_default_zone(), 100)"); + memset(zp, 'z', 100); + + if(malloc_zone_from_ptr(zp) == NULL) { + FAIL("malloc_zone_from_ptr does not recognize an IsoAlloc chunk"); + } + + zp = malloc_zone_realloc(malloc_default_zone(), zp, 1000); + expect_owned(zp, 1000, "malloc_zone_realloc"); + + if(zp[0] != 'z' || zp[99] != 'z') { + FAIL("malloc_zone_realloc lost the contents"); + } + + malloc_zone_free(malloc_zone_from_ptr(zp), zp); + + zp = malloc(32); + expect_owned(zp, 32, "malloc(32)"); + /* This used to abort inside libSystem because no zone + * claimed the pointer */ + malloc_zone_free(malloc_default_zone(), zp); + + zp = malloc_zone_calloc(malloc_default_zone(), 4, 100); + expect_owned(zp, 400, "malloc_zone_calloc"); + free(zp); + + zp = malloc_zone_valloc(malloc_default_zone(), 100); + expect_owned(zp, 100, "malloc_zone_valloc"); + expect_aligned(zp, (size_t) page, "malloc_zone_valloc"); + free(zp); + + zp = malloc_zone_memalign(malloc_default_zone(), 512, 100); + expect_owned(zp, 100, "malloc_zone_memalign"); + expect_aligned(zp, 512, "malloc_zone_memalign"); + free(zp); + + if(malloc_zone_from_ptr(malloc) != NULL) { + FAIL("malloc_zone_from_ptr claimed a code address"); + } + + zp = reallocf(malloc(10), 200); + expect_owned(zp, 200, "reallocf"); + free(zp); + +#if defined(__MAC_14_0) && __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_14_0 + /* Typed memory operations, used by code built with them */ + zp = malloc_type_malloc(300, 0x1234); + expect_owned(zp, 300, "malloc_type_malloc"); + zp = malloc_type_realloc(zp, 600, 0x1234); + expect_owned(zp, 600, "malloc_type_realloc"); + malloc_type_free(zp, 0x1234); + zp = malloc_type_calloc(3, 100, 0x1234); + expect_owned(zp, 300, "malloc_type_calloc"); + free(zp); + zp = malloc_type_zone_malloc(malloc_default_zone(), 300, 0x1234); + expect_owned(zp, 300, "malloc_type_zone_malloc"); + free(zp); +#endif +#endif + + if(iso_mem_usage_fn != NULL) { + (void) iso_mem_usage_fn(); + } + + printf("interpose_check ok\n"); + return 0; +} diff --git a/tests/preload/preload_test.h b/tests/preload/preload_test.h new file mode 100644 index 0000000..c5f56c7 --- /dev/null +++ b/tests/preload/preload_test.h @@ -0,0 +1,71 @@ +/* preload_test.h - Shared helpers for the preload tests + * Copyright 2023 - chris.rohlf@gmail.com + * + * These programs never link against IsoAlloc or include its + * headers. They are built like any program a user might run + * with LD_PRELOAD or DYLD_INSERT_LIBRARIES and reach the + * library only through the libc names and dlsym */ +#pragma once + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +static size_t (*iso_chunksz_fn)(void *); +static uint64_t (*iso_mem_usage_fn)(void); + +#define FAIL(...) \ + do { \ + fprintf(stderr, "FAIL %s:%d ", __FILE__, __LINE__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + exit(1); \ + } while(0) + +/* Resolves the IsoAlloc API from whatever loaded it. Fails + * when the library is not in the process at all */ +static inline void preload_resolve(void) { + iso_chunksz_fn = (size_t(*)(void *)) dlsym(RTLD_DEFAULT, "iso_chunksz"); + iso_mem_usage_fn = (uint64_t(*)(void)) dlsym(RTLD_DEFAULT, "iso_alloc_mem_usage"); + + if(iso_chunksz_fn == NULL) { + FAIL("iso_chunksz not found, libisoalloc is not loaded in this process"); + } +} + +/* A chunk IsoAlloc handed out has a non zero chunk size that + * is at least the request. In a strict build iso_chunksz + * aborts on a pointer from another allocator, in a lenient + * build it returns 0. Either way a foreign pointer fails */ +static inline size_t expect_owned(void *p, size_t at_least, const char *what) { + if(p == NULL) { + FAIL("%s returned NULL", what); + } + + size_t sz = iso_chunksz_fn(p); + + if(sz == 0 || sz < at_least) { + FAIL("%s returned %p which IsoAlloc does not own (chunk size %zu, wanted >= %zu)", what, p, sz, at_least); + } + + return sz; +} + +static inline void expect_aligned(void *p, size_t alignment, const char *what) { + if(((uintptr_t) p & (alignment - 1)) != 0) { + FAIL("%s returned %p which is not %zu byte aligned", what, p, alignment); + } +} + +#ifdef __cplusplus +} +#endif diff --git a/tests/preload/thread_churn.c b/tests/preload/thread_churn.c new file mode 100644 index 0000000..7de0268 --- /dev/null +++ b/tests/preload/thread_churn.c @@ -0,0 +1,64 @@ +/* thread_churn.c - Many threads allocating across every size + * class, which creates zones concurrently. This caught the + * root lock being a no-op on macOS + * Copyright 2023 - chris.rohlf@gmail.com */ + +#include "preload_test.h" +#include +#include + +#define THREADS 8 + +static volatile int stop; + +static void *churn(void *arg) { + unsigned s = (unsigned) (size_t) arg * 7919u + 1u; + void *p[128]; + size_t n[128]; + + while(stop == 0) { + for(int i = 0; i < 128; i++) { + s = s * 1103515245u + 12345u; + size_t limit = (i % 16 == 0) ? 200000 : 2048; + n[i] = 16 + (s >> 8) % limit; + p[i] = malloc(n[i]); + + if(p[i] == NULL) { + FAIL("malloc(%zu) returned NULL", n[i]); + } + + memset(p[i], (int) (i + 1), n[i]); + } + + for(int i = 0; i < 128; i++) { + if(((unsigned char *) p[i])[n[i] - 1] != (unsigned char) (i + 1)) { + FAIL("chunk %p of size %zu was overwritten", p[i], n[i]); + } + + free(p[i]); + } + } + + return NULL; +} + +int main(int argc, char **argv) { + int seconds = (argc > 1) ? atoi(argv[1]) : 2; + pthread_t t[THREADS]; + preload_resolve(); + + for(long i = 0; i < THREADS; i++) { + pthread_create(&t[i], NULL, churn, (void *) i); + } + + struct timespec ts = {seconds, 0}; + nanosleep(&ts, NULL); + stop = 1; + + for(int i = 0; i < THREADS; i++) { + pthread_join(t[i], NULL); + } + + printf("thread_churn ok\n"); + return 0; +} diff --git a/tests/zone_retirement.c b/tests/zone_retirement.c index 1c765ba..6ec9b6a 100644 --- a/tests/zone_retirement.c +++ b/tests/zone_retirement.c @@ -20,11 +20,31 @@ int main(int argc, char *argv[]) { return ERR; } - /* Zone 0 is the first default zone. Retire whatever - * size it holds */ - const size_t sz = root->zones[0].chunk_size; + /* Zone 0 is the first default zone and the index this + * regression is about. It can only retire when nothing else + * holds a chunk in it. On macOS the library interposes the + * system allocator in every program that links it, so + * libSystem keeps a few chunks in the smallest class for the + * life of the process. Then the first default zone that is + * empty stands in, the retirement and index logic under test + * is the same for every index */ + int32_t idx = -1; + + for(int32_t i = 0; i < DEFAULT_ZONE_COUNT; i++) { + if(root->zones[i].af_count == 0) { + idx = i; + break; + } + } + + if(idx < 0) { + LOG("Every default zone holds live chunks, cannot test retirement"); + return ERR; + } + + const size_t sz = root->zones[idx].chunk_size; - const uint64_t chunk_count = root->zones[0].chunk_count; + const uint64_t chunk_count = root->zones[idx].chunk_count; const uint64_t cycles = (chunk_count << root->zone_retirement_shf) + chunk_count; /* iso_free_size() releases chunks immediately (no quarantine) @@ -40,15 +60,17 @@ int main(int argc, char *argv[]) { iso_free_size(q, sz); } - /* Zone 0 should have been retired and replaced in place. If + /* The zone should have been retired and replaced in place. If * alloc_count was never reset then retirement never triggered * and this test is no longer testing anything */ - if(root->zones[0].alloc_count >= cycles) { + if(root->zones[idx].alloc_count >= cycles) { + LOG("Zone %d did not retire, alloc_count %u", idx, root->zones[idx].alloc_count); return ERR; } - /* The replacement zone must keep index 0 */ - if(root->zones[0].index != 0) { + /* The replacement zone must keep its index */ + if(root->zones[idx].index != idx) { + LOG("Zone %d was relabeled with index %u", idx, root->zones[idx].index); return ERR; } diff --git a/utils/run_preload_tests.sh b/utils/run_preload_tests.sh new file mode 100755 index 0000000..7e763ab --- /dev/null +++ b/utils/run_preload_tests.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# Runs the programs in tests/preload with IsoAlloc inserted +# into them the way a user would, LD_PRELOAD on Linux and +# DYLD_INSERT_LIBRARIES on macOS. The programs do not link +# the library. Usage: run_preload_tests.sh [library CFLAGS] +# When the flags contain THREAD_SUPPORT=0 the multi threaded +# tests are skipped, a library built that way is only meant +# for single threaded programs +lib="${1:-build/libisoalloc.so}" +lib_flags="${2:-}" +build_dir="$(dirname "$lib")" + +if [ ! -f "$lib" ]; then + echo "No library at $lib" + exit 1 +fi + +case "$(uname)" in + Darwin) var=DYLD_INSERT_LIBRARIES; lib="$(cd "$build_dir" && pwd)/$(basename "$lib")" ;; + *) var=LD_PRELOAD ;; +esac + +# macOS has no timeout(1). A test that hangs is a failure, +# which is the whole point of the fork test +run_with_timeout() { + local secs=$1 + shift + env "$var=$lib" "$@" & + local pid=$! + # The killer closes stdout and stderr, otherwise the output + # capture in the caller waits for the full timeout + ( sleep "$secs"; kill -9 "$pid" 2>/dev/null ) >/dev/null 2>&1 & + local killer=$! + wait "$pid" + local rc=$? + pkill -P "$killer" 2>/dev/null + kill "$killer" 2>/dev/null + wait "$killer" 2>/dev/null + return $rc +} + +tests=("preload_interpose_check" "preload_foreign_ptr" "preload_cpp_hooks" "preload_exit_order" "preload_thread_churn" "preload_fork_safety") + +case "$lib_flags" in + *THREAD_SUPPORT=0*) + echo "Library built without THREAD_SUPPORT, skipping the multi threaded tests" + export ISO_PRELOAD_NO_THREADS=1 + tests=("preload_interpose_check" "preload_foreign_ptr" "preload_cpp_hooks" "preload_exit_order") + ;; +esac +failure=0 +succeeded=0 + +echo "Running preload tests with $var=$lib" + +for t in "${tests[@]}"; do + echo -n "Running $t" + out=$(run_with_timeout 120 "$build_dir/$t" 2>&1) + ret=$? + + if [ $ret -ne 0 ]; then + echo "... Failed (exit $ret)" + echo "$out" | tail -20 + failure=$((failure+1)) + else + echo "... Succeeded" + succeeded=$((succeeded+1)) + fi +done + +echo "Preload tests: $succeeded succeeded, $failure failed" + +if [ $failure -ne 0 ]; then + exit 1 +fi