blob: db16d8492a564bd6a19fcf73f91e9d7132cd458e [file] [log] [blame]
Jeremy Kerr4cdc2002019-02-07 16:49:12 +08001/* SPDX-License-Identifier: Apache-2.0 */
2
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
8struct {
Jeremy Kerr3a666ce2019-03-06 09:18:50 +08009 void *(*m_alloc)(size_t);
10 void (*m_free)(void *);
11 void *(*m_realloc)(void *, size_t);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080012} alloc_ops = {
Jeremy Kerr3cb4eee2019-03-06 09:15:47 +080013#ifndef MCTP_NO_DEFAULT_ALLOC
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080014 malloc,
15 free,
16 realloc,
Jeremy Kerr3cb4eee2019-03-06 09:15:47 +080017#endif
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080018};
19
20/* internal-only allocation functions */
21void *__mctp_alloc(size_t size)
22{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080023 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 Kerr4cdc2002019-02-07 16:49:12 +080027 assert(0);
28}
29
30void __mctp_free(void *ptr)
31{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080032 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 Kerr4cdc2002019-02-07 16:49:12 +080036 else
37 assert(0);
38}
39
40void *__mctp_realloc(void *ptr, size_t size)
41{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080042 if (alloc_ops.m_realloc)
43 return alloc_ops.m_realloc(ptr, size);
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080044 assert(0);
45}
46
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080047void mctp_set_alloc_ops(void *(*m_alloc)(size_t),
48 void (*m_free)(void *),
49 void *(m_realloc)(void *, size_t))
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080050{
Jeremy Kerr3a666ce2019-03-06 09:18:50 +080051 alloc_ops.m_alloc = m_alloc;
52 alloc_ops.m_free = m_free;
53 alloc_ops.m_realloc = m_realloc;
Jeremy Kerr4cdc2002019-02-07 16:49:12 +080054}