-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
127 lines (110 loc) · 2.51 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include "main.h"
#include <dlfcn.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int foo_s; /// Interface source
int *foo; /// Interface pointer
struct plugin_data {
void *handle;
void (*fun) (void);
};
/**
* Symbol importer. Called by plugins, it returns a pointer to the requested
* interface (here we have only one, foo).
*/
void *plugin_import_symbol(void)
{
return foo;
}
/**
* Convenience function. Prints the value of foo and increases it.
*/
void printfoo(void)
{
if (foo)
printf("(main) foo++: %d.\n", (*foo)++);
else
printf("(main) foo is null.\n");
}
/**
* This function is a test-case against FreeBSD mixing up functions with the
* same name in core and plugin.
*/
void fun(void)
{
printf("This is fun from main.\n");
}
/**
* Plugin loader. Loads a plugin by name.
*/
struct plugin_data *load_plugin(const char *name, struct plugin_data *data)
{
void **pimport = NULL;
void (*pinit) (void) = NULL;
char buf[256];
snprintf(buf, 256, "./%s.%s", name, EXPAND_AND_QUOTE(PLUGINEXT));
data->handle = dlopen(buf, RTLD_NOW);
if (!data->handle) {
printf("%s: dlopen error: %s\n", name, dlerror());
return NULL;
}
pimport = dlsym(data->handle, "import_symbol");
if (!pimport) {
printf("%s: missing symbol import_symbol\n", name);
return NULL;
}
*pimport = plugin_import_symbol;
pinit = dlsym(data->handle, "HPM_shared_symbols");
if (!pinit) {
printf("%s: missing symbol HPM_shared_symbols\n", name);
return NULL;
}
pinit();
data->fun = dlsym(data->handle, "fun");
if (!data->fun) {
printf("%s: missing symbol fun\n", name);
return NULL;
}
printf("Plugin %s.%s loaded.\n", name, EXPAND_AND_QUOTE(PLUGINEXT));
return data;
}
int main(int argc, char *argv[])
{
int i;
struct plugin_data *handles = malloc(sizeof(struct plugin_data) * (argc-1));
if (argc < 2) {
printf("Usage: %s plugin1 plugin2 ...\n", argv[0]);
return EXIT_FAILURE;
}
// Connect and initialize symbols
foo = &foo_s;
*foo = 1;
// Show initial values
fun();
printfoo();
printf("--------------\n");
// Load plugins
for (i = 0; i < argc - 1; ++i) {
if (!load_plugin(argv[i+1], &handles[i])) {
return EXIT_FAILURE;
}
}
printf("--------------\n");
// Execute plugin functions
for (i = 0; i < argc - 1; ++i) {
printf("Plugin: %s\n", argv[i+1]);
handles[i].fun();
printfoo();
printf("--------------\n");
}
// Show final values again
fun();
printfoo();
// Unload plugins
for (i = 0; i < argc - 1; ++i) {
dlclose(handles[i].handle);
}
free(handles);
return EXIT_SUCCESS;
}