common/autodata: autodata replacement which uses __attribute__((constructor))

This is a GCC extension, but avoids much other messiness.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
This commit is contained in:
Rusty Russell 2021-09-21 16:53:07 +09:30 committed by Christian Decker
parent 5b644a2319
commit b594c53771
3 changed files with 67 additions and 0 deletions

View File

@ -1,6 +1,7 @@
COMMON_SRC_NOGEN := \ COMMON_SRC_NOGEN := \
common/addr.c \ common/addr.c \
common/amount.c \ common/amount.c \
common/autodata.c \
common/base32.c \ common/base32.c \
common/base64.c \ common/base64.c \
common/bech32.c \ common/bech32.c \

40
common/autodata.c Normal file
View File

@ -0,0 +1,40 @@
#include "config.h"
#include <assert.h>
#include <ccan/strmap/strmap.h>
#include <common/autodata.h>
struct typereg {
size_t num;
const void **ptrs;
};
static STRMAP(struct typereg *) typemap;
void autodata_register_(const char *typename, const void *ptr)
{
struct typereg *t;
assert(ptr);
t = strmap_get(&typemap, typename);
if (!t) {
t = malloc(sizeof(struct typereg));
t->num = 0;
t->ptrs = NULL;
strmap_add(&typemap, typename, t);
}
t->ptrs = realloc(t->ptrs, (t->num + 1) * sizeof(*t->ptrs));
t->ptrs[t->num] = ptr;
t->num++;
}
void *autodata_get_(const char *typename, size_t *nump)
{
struct typereg *t = strmap_get(&typemap, typename);
if (!t) {
*nump = 0;
return NULL;
}
*nump = t->num;
return t->ptrs;
}

26
common/autodata.h Normal file
View File

@ -0,0 +1,26 @@
#ifndef LIGHTNING_COMMON_AUTODATA_H
#define LIGHTNING_COMMON_AUTODATA_H
#include "config.h"
#include <ccan/compiler/compiler.h>
#include <ccan/cppmagic/cppmagic.h>
#define AUTODATA_TYPE(name, type) \
static inline void register_autotype_##name(const type *t) { \
autodata_register_(#name, t); \
} \
typedef type autodata_##name##_
/* This uses GCC's constructor attribute */
#define AUTODATA(name, ptr) \
static __attribute__((constructor)) NEEDED \
void CPPMAGIC_GLUE2(register_one_##name,__COUNTER__)(void) { \
register_autotype_##name(ptr); \
}
#define autodata_get(name, nump) \
((autodata_##name##_ **)autodata_get_(#name, (nump)))
void autodata_register_(const char *typename, const void *ptr);
void *autodata_get_(const char *typename, size_t *nump);
#endif /* LIGHTNING_COMMON_AUTODATA_H */