Skip to content

Instantly share code, notes, and snippets.

@lyon-fnal
Last active December 15, 2020 04:35
Show Gist options
  • Select an option

  • Save lyon-fnal/e7e31452b82dc65e8fb9fbaa26022fb7 to your computer and use it in GitHub Desktop.

Select an option

Save lyon-fnal/e7e31452b82dc65e8fb9fbaa26022fb7 to your computer and use it in GitHub Desktop.
Trying LD_PRELOAD with Julia
/* build with gcc -shared -fPIC -o base.so base.c */
#include <stdio.h>
void doTheThing() {
printf("BASE\n");
}
/* build with gcc -shared -fPIC -ldl -o inject.so inject.c */
/* See http://www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/ */
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
typedef void (*real_doTheThing_t)();
/* Call the real "doTheThing" in the regular library (base.so, in this case) */
void real_doTheThing() {
((real_doTheThing_t)dlsym(RTLD_NEXT, "doTheThing"))();
}
void doTheThing() {
printf("INJECT ");
real_doTheThing();
}
#= Run with
LD_PRELOAD=./inject.so julia try.jl
=#
using Libdl
# We must use LD_PRELOAD to make the wrapping in inject.c work (we can't just dlopen("./inject.so") )
# Load the base library
base = "./base.so"
b = dlopen(base, RTLD_GLOBAL | RTLD_DEEPBIND | RTLD_LAZY) # Need RTLD_GLOBAL so ccall(:fcn, ...)
# can find :fcn without specifying the library
# RTLD_DEEPBIND doesn't seem to matter
# This will honor LD_PRELOAD
ccall(:doTheThing, Cvoid, ())
# This will not honor LD_PRELOAD since we are specifying the library to use
ccall((:doTheThing, "./base.so"), Cvoid, ())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment