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