-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathalloc.c
106 lines (92 loc) · 2.18 KB
/
alloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */
#include <assert.h>
#include "libmctp.h"
#include "libmctp-alloc.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "compiler.h"
#if defined(MCTP_DEFAULT_ALLOC) && defined(MCTP_CUSTOM_ALLOC)
#error Default and Custom alloc are incompatible
#endif
#ifdef MCTP_DEFAULT_ALLOC
static void *default_msg_malloc(size_t size, void *ctx __unused)
{
void *ptr = __mctp_alloc(size);
return ptr;
}
static void default_msg_free(void *msg, void *ctx __unused)
{
__mctp_free(msg);
}
#endif
/* Allocators provided as functions to call */
#ifdef MCTP_CUSTOM_ALLOC
extern void *mctp_custom_malloc(size_t size);
extern void mctp_custom_free(void *ptr);
extern void *mctp_custom_msg_alloc(size_t size, void *ctx);
extern void mctp_custom_msg_free(void *msg, void *ctx);
#endif
#ifdef MCTP_CUSTOM_ALLOC
const
#endif
struct {
void *(*m_alloc)(size_t);
void (*m_free)(void *);
/* Final argument is ctx */
void *(*m_msg_alloc)(size_t, void *);
void (*m_msg_free)(void *, void *);
} alloc_ops = {
#ifdef MCTP_DEFAULT_ALLOC
malloc,
free,
default_msg_malloc,
default_msg_free,
#endif
#ifdef MCTP_CUSTOM_ALLOC
mctp_custom_malloc,
mctp_custom_free,
mctp_custom_msg_alloc,
mctp_custom_msg_free,
#endif
};
/* internal-only allocation functions */
void *__mctp_alloc(size_t size)
{
if (alloc_ops.m_alloc)
return alloc_ops.m_alloc(size);
assert(0);
return NULL;
}
void __mctp_free(void *ptr)
{
if (alloc_ops.m_free)
alloc_ops.m_free(ptr);
else
assert(0);
}
void *__mctp_msg_alloc(size_t size, struct mctp *mctp)
{
void *ctx = mctp_get_alloc_ctx(mctp);
if (alloc_ops.m_msg_alloc)
return alloc_ops.m_msg_alloc(size, ctx);
assert(0);
return NULL;
}
void __mctp_msg_free(void *ptr, struct mctp *mctp)
{
void *ctx = mctp_get_alloc_ctx(mctp);
if (alloc_ops.m_msg_free)
alloc_ops.m_msg_free(ptr, ctx);
}
#ifndef MCTP_CUSTOM_ALLOC
void mctp_set_alloc_ops(void *(*m_alloc)(size_t), void (*m_free)(void *),
void *(*m_msg_alloc)(size_t, void *),
void (*m_msg_free)(void *, void *))
{
alloc_ops.m_alloc = m_alloc;
alloc_ops.m_free = m_free;
alloc_ops.m_msg_alloc = m_msg_alloc;
alloc_ops.m_msg_free = m_msg_free;
}
#endif // MCTP_CUSTOM_ALLOC