-
Notifications
You must be signed in to change notification settings - Fork 0
/
dlmod.c
83 lines (72 loc) · 1.88 KB
/
dlmod.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
/******************************************************************************
* Copyright (C) 2014-2015
* file: libdlmod.c
* author: gozfree <[email protected]>
* created: 2015-11-09 18:51
* updated: 2015-11-09 18:51
******************************************************************************/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include "dlmod.h"
#include "log.h"
#define CAPABILITY "capability"
typedef int (*get_capability)(struct capability_desc *desc);
struct dl_handle *dl_load(const char *path)
{
void *handle = dlopen(path, RTLD_NOW);
if (!handle) {
log_error("dlopen %s failed: %s", path, dlerror());
return NULL;
}
struct dl_handle *dl = calloc(1, sizeof(struct dl_handle));
dl->handle = handle;
return dl;
}
void dl_unload(struct dl_handle *dl)
{
if (!dl) {
return;
}
if (dl->handle) {
dlclose(dl->handle);
}
}
int dl_capability(struct dl_handle *dl, const char *mod_name,
struct capability_desc *desc)
{
if (!dl) {
return -1;
}
char *err = NULL;
char symbol[512];
snprintf(symbol, sizeof(symbol), "%s_%s", mod_name, CAPABILITY);
get_capability get_cap = (get_capability)dlsym(dl->handle, symbol);
if (((err = dlerror()) != NULL)) {
log_error("Failed to get symbol %s: %s\n", symbol, err);
return -1;
}
get_cap(desc);
return 0;
}
void *dl_get_func(struct dl_handle *dl, const char *name)
{
if (!dl) {
return NULL;
}
void *func = dlsym(dl->handle, name);
if (!func) {
log_error("Failed to get symbol %s: %s\n", name, dlerror());
}
return func;
}
void *dl_override(const char *name)
{
void *sym = dlsym(RTLD_NEXT, name);
if (!sym) {
log_error("Failed override symbol %s: %s\n", name, dlerror());
abort();
}
return sym;
}