blob: 84c3f652f6735b59b495a8a2b8fba6f4d8187178 [file] [log] [blame]
Jeremy Kerr3d36ee22019-05-30 11:15:37 +08001/* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */
Jeremy Kerr4cdc2002019-02-07 16:49:12 +08002
3#include <assert.h>
4
Jeremy Kerr3a666ce2019-03-06 09:18:50 +08005#include "libmctp.h"
Jeremy Kerr4cdc2002019-02-07 16:49:12 +08006#include "libmctp-alloc.h"
7
Jeremy Kerrc7e764a2019-05-28 16:49:03 +08008#ifdef HAVE_CONFIG_H
9#include "config.h"
10#endif
11
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080012struct {
Andrew Jeffery23496bf2022-09-30 14:17:09 +093013 void *(*m_alloc)(size_t);
14 void (*m_free)(void *);
15 void *(*m_realloc)(void *, size_t);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080016} alloc_ops = {
Jeremy Kerrc7e764a2019-05-28 16:49:03 +080017#ifdef MCTP_DEFAULT_ALLOC
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080018 malloc,
19 free,
20 realloc,
Jeremy Kerr3cb4eee2019-03-06 09:15:47 +080021#endif
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080022};
23
24/* internal-only allocation functions */
25void *__mctp_alloc(size_t size)
26{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080027 if (alloc_ops.m_alloc)
28 return alloc_ops.m_alloc(size);
29 if (alloc_ops.m_realloc)
30 return alloc_ops.m_realloc(NULL, size);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080031 assert(0);
Andrew Jeffery5e56cd82020-03-10 22:23:05 +103032 return NULL;
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080033}
34
35void __mctp_free(void *ptr)
36{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080037 if (alloc_ops.m_free)
38 alloc_ops.m_free(ptr);
39 else if (alloc_ops.m_realloc)
40 alloc_ops.m_realloc(ptr, 0);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080041 else
42 assert(0);
43}
44
45void *__mctp_realloc(void *ptr, size_t size)
46{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080047 if (alloc_ops.m_realloc)
48 return alloc_ops.m_realloc(ptr, size);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080049 assert(0);
Andrew Jeffery5e56cd82020-03-10 22:23:05 +103050 return NULL;
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080051}
52
Andrew Jeffery23496bf2022-09-30 14:17:09 +093053void mctp_set_alloc_ops(void *(*m_alloc)(size_t), void (*m_free)(void *),
54 void *(m_realloc)(void *, size_t))
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080055{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080056 alloc_ops.m_alloc = m_alloc;
57 alloc_ops.m_free = m_free;
58 alloc_ops.m_realloc = m_realloc;
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080059}