blob: 9edfd6c629c2d927d9f8bdeff924c7ed522d2e2b [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 {
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080013 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);
32}
33
34void __mctp_free(void *ptr)
35{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080036 if (alloc_ops.m_free)
37 alloc_ops.m_free(ptr);
38 else if (alloc_ops.m_realloc)
39 alloc_ops.m_realloc(ptr, 0);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080040 else
41 assert(0);
42}
43
44void *__mctp_realloc(void *ptr, size_t size)
45{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080046 if (alloc_ops.m_realloc)
47 return alloc_ops.m_realloc(ptr, size);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080048 assert(0);
49}
50
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080051void mctp_set_alloc_ops(void *(*m_alloc)(size_t),
52 void (*m_free)(void *),
53 void *(m_realloc)(void *, size_t))
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080054{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080055 alloc_ops.m_alloc = m_alloc;
56 alloc_ops.m_free = m_free;
57 alloc_ops.m_realloc = m_realloc;
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080058}