Question

I need to change reference of a function in a Mac OS process at runtime to a custom function defined in my own custom dylib. I kept the new function signature same as the original. For example I need to change "open" function to "myopen" function.

I tried processing __LINKEDIT segment to get the dynamic symbol table and string table. I used following pointers, 1. the VMAddrress from __LINKEDIT segment, 2. mach_header and vmaddr_slide from the "_dyld_register_func_for_add_image" callback, 3. symoff and stroff from symtab_command.

But I am unable to get the symbol table and string table mentioned in the __LINKEDIT segment. Can someone throw some light on this? Thanks in advance.

No correct solution

OTHER TIPS

If the function in question is a library function, and not statically compiled into the executable, you don't need to do any of that - you can use function interposing, instead. Specifically, add this to your library:

  // The attribute creates a Mach-O Section in your library - q.v. libgmalloc.dylib for 
  // a nice example
    static const interpose_t interposing_functions[] \
        __attribute__ ((section("__DATA, __interpose"))) = {
            { (void *)my_open,  (void *)open  },
            { (void *)my_close, (void *)close }, // .. etc
        };


int  my_open(const char *path, int flags, mode_t mode)
{

    int rc;
    // Prolog - do something before open

    rc = open(path, flags, mode); // call real open

    // Epilog - record rc, etc..    

    return rc;
}

There are several excellent books on OS X internals which can provide you with samples, though apparently according to S.O site policies we can't link you to them. That said, the above code snippet should work. Bear in mind, that this won't work on calls to open performed by other dylibs (though there are more complicated ways to get that, as well)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top