What is the exact equivalent to LD_PRELOAD on OSX?

horseyguy picture horseyguy · Dec 15, 2011 · Viewed 11.6k times · Source

I am using LD_PRELOAD to hook a library function, and in Linux it works perfectly. But I cannot figure out how to do the equivalent in OSX.

The setup I have on Linux is as follows:

The code is:

#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <unistd.h>
#include <ruby.h>

void
rb_raise(unsigned long exc, const char *fmt, ...)
{
  static void (*libruby_rb_raise)
    (unsigned long exc, const char *fmt, ...) = NULL;

  void * handle;
  char * error;

  if (!libruby_rb_raise) {
    handle = dlopen("/path/to/libruby.so",
                    RTLD_LAZY);
    if (!handle) {
      fputs(dlerror(), stderr);
      exit(1);
    }
    libruby_rb_raise = dlsym(handle, "rb_raise");
    if ((error = dlerror()) != NULL) {
      fprintf(stderr, "%s\n", error);
      exit(1);
    }
  }

  // ...code... 

  return Qnil;
}

Which I then compile with:

gcc -Wall -O2 -fpic -shared -ldl -g -I/path/to/includes/ -o raise_shim.so raise_shim.c

I then execute with:

LD_PRELOAD=./raise_shim.so ruby

All of the above works well on Linux, what is the equivalent for each step to get this working on OSX? I have googled this and have not been able to get it to work with the information provided as the info for some of the steps are missing.

Thanks in advance!

Answer

Dan Fego picture Dan Fego · Dec 15, 2011

Take a look at DYLD_INSERT_LIBRARIES. That's the variable you're looking for.

See also this answer.