Skip to content

Instantly share code, notes, and snippets.

@jjpe
Created May 2, 2015 17:46
Show Gist options
  • Save jjpe/df251ba65a8c34f9412e to your computer and use it in GitHub Desktop.
Save jjpe/df251ba65a8c34f9412e to your computer and use it in GitHub Desktop.
Calling rand using ::dlsym()
#include <iostream>
#include <ffi.h>
#include <dlfcn.h>
int main(int argc, const char* argv[]) {
char* err_str;
err_str = ::dlerror();
if (err_str) {
std::cout << "dlsym: pre error: " << err_str << "\n";
}
void *handle = 0;
handle = ::dlopen(0,RTLD_LAZY|RTLD_GLOBAL);
void *fn_ptr = ::dlsym(handle, "rand");
void (*function)() = reinterpret_cast<void (*)()>(fn_ptr);
ffi_cif *cif = new ffi_cif;
uint32_t nargs = 0;
void *args[nargs];
int32_t raw_args[nargs];
for (uint32_t i = 0; i < nargs; i++) {
args[i] = static_cast<void*>(&raw_args[i]);
}
ffi_type rtype = ffi_type_uint32;
ffi_type **types = new ffi_type*[nargs];
ffi_status s = ffi_prep_cif(cif, FFI_DEFAULT_ABI, nargs, &rtype, types);
if (s == FFI_OK) {
std::cout << "cif: cif is OK\n";
} else if (s == FFI_BAD_TYPEDEF) {
std::cout << "cif: One of the ffi_type objects is incorrect\n";
} else if (s == FFI_BAD_ABI) {
std::cout << "cif: The abi parameter is invalid\n";
}
int value = 0;
ffi_call(cif, function, &value, args);
std::cout << "rand val: " << value << "\n";
err_str = ::dlerror();
if (err_str) {
std::cout << "dlsym: post error: " << err_str << "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment