0

I need to change to reference of a function in a mach-o binary to a custom function defined in my own dylib. The process I am now following is,

  1. Replacing references to older functions to the new one. e.g _fopen to _mopen using sed.

  2. I open the mach-o binary in MachOView to find the address of the entities I want to change. I then manually change the information in the binary using a hex editor.

Is there a way I can automate this process i.e write a program to read the symbols, and dynamic loading info and then change them in the executable. I was looking at the mach-o header files at /usr/include/mach-o but am not entire sure how to use them to get this information. Do there exist any libraries present - C or python which help do the same?

varrunr
  • 845
  • 1
  • 11
  • 19

2 Answers2

2

varrunr - you can easily achieve most if not all of the functionality using DYLD's interposition. You create your own library, and declare your interposing functions, like so

// This is the expected interpose structure
typedef struct interpose_s {
    void *new_func;
    void *orig_func;
} interpose_t;

static const interpose_t interposing_functions[] \
    __attribute__ ((section("__DATA, __interpose"))) = {
        { (void *)my_open,  (void *) open  }
    };

.. and you just implement your open. In the interposing functions all references to the original will work - which makes this ideal for wrappers. And, you can insert your dylib forcefully using DYLD_INSERT_LIBRARIES (same principle as LD_PRELOAD on Linux).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Technologeeks
  • 181
  • 1
  • 4
  • Thanks. Is there any online documentation on interposition? – varrunr Sep 27 '12 at 14:49
  • Only documentation I know of is in that book, which you can find or buy an eBook of, I guess. Apple uses interposing in libgmalloc (The malloc guard library), but other than that it's obviously left just for developer use. – Technologeeks Sep 28 '12 at 13:35
2

interesting question, I am trying to do something similar to static lib; see if this helps

Prashant Rane
  • 436
  • 4
  • 11