1 /* $NetBSD: jemalloc_shim.h,v 1.4 2025/01/26 16:25:37 christos Exp $ */ 2 3 /* 4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC") 5 * 6 * SPDX-License-Identifier: MPL-2.0 7 * 8 * This Source Code Form is subject to the terms of the Mozilla Public 9 * License, v. 2.0. If a copy of the MPL was not distributed with this 10 * file, you can obtain one at https://mozilla.org/MPL/2.0/. 11 * 12 * See the COPYRIGHT file distributed with this work for additional 13 * information regarding copyright ownership. 14 */ 15 16 #pragma once 17 18 #if !defined(HAVE_JEMALLOC) 19 20 #include <stddef.h> 21 #include <string.h> 22 23 #include <isc/util.h> 24 25 const char *malloc_conf = NULL; 26 27 #define MALLOCX_ZERO ((int)0x40) 28 #define MALLOCX_TCACHE_NONE (0) 29 #define MALLOCX_ARENA(a) (0) 30 31 #include <stdlib.h> 32 33 typedef union { 34 size_t size; 35 max_align_t __alignment; 36 } size_info; 37 38 static inline void * 39 mallocx(size_t size, int flags) { 40 void *ptr = NULL; 41 42 size_t bytes = ISC_CHECKED_ADD(size, sizeof(size_info)); 43 size_info *si = malloc(bytes); 44 INSIST(si != NULL); 45 46 si->size = size; 47 ptr = &si[1]; 48 49 if ((flags & MALLOCX_ZERO) != 0) { 50 memset(ptr, 0, size); 51 } 52 53 return ptr; 54 } 55 56 static inline void 57 sdallocx(void *ptr, size_t size ISC_ATTR_UNUSED, int flags ISC_ATTR_UNUSED) { 58 size_info *si = &(((size_info *)ptr)[-1]); 59 60 free(si); 61 } 62 63 static inline size_t 64 sallocx(void *ptr, int flags ISC_ATTR_UNUSED) { 65 size_info *si = &(((size_info *)ptr)[-1]); 66 67 return si[0].size; 68 } 69 70 static inline void * 71 rallocx(void *ptr, size_t size, int flags) { 72 size_info *si = realloc(&(((size_info *)ptr)[-1]), size + sizeof(*si)); 73 INSIST(si != NULL); 74 75 if ((flags & MALLOCX_ZERO) != 0 && size > si->size) { 76 memset((uint8_t *)si + sizeof(*si) + si->size, 0, 77 size - si->size); 78 } 79 80 si->size = size; 81 ptr = &si[1]; 82 83 return ptr; 84 } 85 86 #endif /* !defined(HAVE_JEMALLOC) */ 87