Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the exact equivalent to LD_PRELOAD on OSX?

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!

like image 324
horseyguy Avatar asked Dec 15 '11 03:12

horseyguy


People also ask

What is ld so PRELOAD?

Additionally, the ld. so. preload file causes a system-wide configuration change, resulting in shared objects being preloaded by any binary on the system. Linux Dynamic Linker Hijacking in Action. Dynamic linker hijacking is often utilised by Linux malware to install rootkits on the target system.

How does Ld_preload work?

LD_PRELOAD allows you to override symbols in any library by specifying your new function in a shared object. When you run LD_PRELOAD=/path/to/my/free.so /bin/mybinary , /path/to/my/free.so is loaded before any other library, including libc. When mybinary is executed, it uses your custom function for free .


1 Answers

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

See also this answer.

like image 181
Dan Fego Avatar answered Nov 15 '22 23:11

Dan Fego