-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmgzd.h
75 lines (63 loc) · 2.2 KB
/
mgzd.h
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
#ifndef __MGZD_H
#define __MGZD_H
/*****************************************************************************\
* Qemu Simulation Framework (qsim) *
* Qsim is a modified version of the Qemu emulator (www.qemu.org), coupled *
* a C++ API, for the use of computer architecture researchers. *
* *
* This work is licensed under the terms of the GNU GPL, version 2. See the *
* COPYING file in the top-level directory. *
\*****************************************************************************/
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <dlfcn.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static const char* TMP_DIR = "/tmp";
static const char* TMP_PFX = "qsim_tmp";
namespace Mgzd {
struct lib_t {
void* handle;
std::string file;
};
static lib_t open(const char *libfile) {
lib_t lib;
// Make temporary copy of libfile, so opening multiple copies of the same
// file results in independent copies of global variables.
const char* tmp_filename_ptr = tempnam(TMP_DIR, TMP_PFX);
lib.file = tmp_filename_ptr;
free((void *)tmp_filename_ptr);
std::ostringstream cp_command;
cp_command << "cp " << libfile << ' ' << lib.file;
int r;
if ((r = system(cp_command.str().c_str())) != 0) {
std::cerr << "system(\"" << cp_command.str()
<< "\") returned " << r <<".\n";
exit(1);
}
lib.handle = dlopen(lib.file.c_str(), RTLD_NOW|RTLD_LOCAL);
if (lib.handle == NULL) {
std::cerr << "dlopen(\"" << lib.file.c_str() << "\") failed: "
<< dlerror() << '\n';
}
return lib;
}
static void close(lib_t lib) {
dlclose(lib.handle);
unlink(lib.file.c_str());
}
template <typename T> static void sym(T *&ret,
const lib_t lib,
const char *sym) {
(void*&)ret = dlsym(lib.handle, sym);
if (char *err = dlerror()) {
std::cerr << "dlsym(\"" << lib.handle << "\", \"" << sym
<< "\") failed: " << err << '\n';
exit(1);
}
}
};
#endif