Jeremy Kerr | 4cdc200 | 2019-02-07 16:49:12 +0800 | [diff] [blame] | 1 | /* SPDX-License-Identifier: Apache-2.0 */ |
| 2 | |
| 3 | #include <assert.h> |
| 4 | |
| 5 | #include "libmctp-alloc.h" |
| 6 | |
| 7 | struct { |
| 8 | void *(*alloc)(size_t); |
| 9 | void (*free)(void *); |
| 10 | void *(*realloc)(void *, size_t); |
| 11 | } alloc_ops = { |
Jeremy Kerr | 3cb4eee | 2019-03-06 09:15:47 +0800 | [diff] [blame^] | 12 | #ifndef MCTP_NO_DEFAULT_ALLOC |
Jeremy Kerr | 4cdc200 | 2019-02-07 16:49:12 +0800 | [diff] [blame] | 13 | malloc, |
| 14 | free, |
| 15 | realloc, |
Jeremy Kerr | 3cb4eee | 2019-03-06 09:15:47 +0800 | [diff] [blame^] | 16 | #endif |
Jeremy Kerr | 4cdc200 | 2019-02-07 16:49:12 +0800 | [diff] [blame] | 17 | }; |
| 18 | |
| 19 | /* internal-only allocation functions */ |
| 20 | void *__mctp_alloc(size_t size) |
| 21 | { |
| 22 | if (alloc_ops.alloc) |
| 23 | return alloc_ops.alloc(size); |
| 24 | if (alloc_ops.realloc) |
| 25 | return alloc_ops.realloc(NULL, size); |
| 26 | assert(0); |
| 27 | } |
| 28 | |
| 29 | void __mctp_free(void *ptr) |
| 30 | { |
| 31 | if (alloc_ops.free) |
| 32 | alloc_ops.free(ptr); |
| 33 | else if (alloc_ops.realloc) |
| 34 | alloc_ops.realloc(ptr, 0); |
| 35 | else |
| 36 | assert(0); |
| 37 | } |
| 38 | |
| 39 | void *__mctp_realloc(void *ptr, size_t size) |
| 40 | { |
| 41 | if (alloc_ops.realloc) |
| 42 | return alloc_ops.realloc(ptr, size); |
| 43 | assert(0); |
| 44 | } |
| 45 | |
| 46 | void mctp_set_alloc_ops(void *(*alloc)(size_t), |
| 47 | void (*free)(void *), |
| 48 | void *(realloc)(void *, size_t)) |
| 49 | { |
| 50 | alloc_ops.alloc = alloc; |
| 51 | alloc_ops.free = free; |
| 52 | alloc_ops.realloc = realloc; |
| 53 | } |