Skip to content

Commit b594c53

Browse files
rustyrussellcdecker
authored andcommitted
common/autodata: autodata replacement which uses __attribute__((constructor))
This is a GCC extension, but avoids much other messiness. Signed-off-by: Rusty Russell <[email protected]>
1 parent 5b644a2 commit b594c53

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

common/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
COMMON_SRC_NOGEN := \
22
common/addr.c \
33
common/amount.c \
4+
common/autodata.c \
45
common/base32.c \
56
common/base64.c \
67
common/bech32.c \

common/autodata.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include "config.h"
2+
#include <assert.h>
3+
#include <ccan/strmap/strmap.h>
4+
#include <common/autodata.h>
5+
6+
struct typereg {
7+
size_t num;
8+
const void **ptrs;
9+
};
10+
11+
static STRMAP(struct typereg *) typemap;
12+
13+
void autodata_register_(const char *typename, const void *ptr)
14+
{
15+
struct typereg *t;
16+
assert(ptr);
17+
18+
t = strmap_get(&typemap, typename);
19+
if (!t) {
20+
t = malloc(sizeof(struct typereg));
21+
t->num = 0;
22+
t->ptrs = NULL;
23+
strmap_add(&typemap, typename, t);
24+
}
25+
26+
t->ptrs = realloc(t->ptrs, (t->num + 1) * sizeof(*t->ptrs));
27+
t->ptrs[t->num] = ptr;
28+
t->num++;
29+
}
30+
31+
void *autodata_get_(const char *typename, size_t *nump)
32+
{
33+
struct typereg *t = strmap_get(&typemap, typename);
34+
if (!t) {
35+
*nump = 0;
36+
return NULL;
37+
}
38+
*nump = t->num;
39+
return t->ptrs;
40+
}

common/autodata.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#ifndef LIGHTNING_COMMON_AUTODATA_H
2+
#define LIGHTNING_COMMON_AUTODATA_H
3+
#include "config.h"
4+
#include <ccan/compiler/compiler.h>
5+
#include <ccan/cppmagic/cppmagic.h>
6+
7+
#define AUTODATA_TYPE(name, type) \
8+
static inline void register_autotype_##name(const type *t) { \
9+
autodata_register_(#name, t); \
10+
} \
11+
typedef type autodata_##name##_
12+
13+
/* This uses GCC's constructor attribute */
14+
#define AUTODATA(name, ptr) \
15+
static __attribute__((constructor)) NEEDED \
16+
void CPPMAGIC_GLUE2(register_one_##name,__COUNTER__)(void) { \
17+
register_autotype_##name(ptr); \
18+
}
19+
20+
#define autodata_get(name, nump) \
21+
((autodata_##name##_ **)autodata_get_(#name, (nump)))
22+
23+
void autodata_register_(const char *typename, const void *ptr);
24+
void *autodata_get_(const char *typename, size_t *nump);
25+
26+
#endif /* LIGHTNING_COMMON_AUTODATA_H */

0 commit comments

Comments
 (0)