Changing function reference in Mach-o binary

2019-06-13 16:55发布

问题:

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?

回答1:

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



回答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).