Using dynamic link library loaded by LC_LOAD_DYLIB to insert C functions

First, I want to intercept an arbitrary standard C function (like fopen, read, write, malloc, ...) of an iOS application.

I have libtest.dylib with this code:

typedef struct interpose_s {
    void *new_func;
    void *orig_func;
} interpose_t;


FILE *vg_fopen(const char * __restrict, const char * __restrict);

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

FILE *vg_fopen(const char * __restrict path, const char * __restrict mode) {
    printf("vg_fopen");
    return fopen(path, mode);
}

      

After compiling dylib, I go to the host iOS app binary and add LC_LOAD_DYLIB to the end of the LC_LOAD_COMMANDS list and point it to @ executable_path / libtest.dylib

I expect it to override fopen's implementation and print "vg_fopen" whenever fopen is called. However, I don't understand, so the intervention could have been unsuccessful.

I would like to know what is the reason. This is for internal development only for teaching, so please do not mention the impact or warn me about misuse.

Thanks in advance.

+3


source to share


1 answer


From dyld

source
:

// link any inserted libraries
// do this after linking main executable so that any dylibs pulled in by inserted 
// dylibs (e.g. libSystem) will not be in front of dylibs the program uses
if ( sInsertedDylibCount > 0 ) {
    for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
        ImageLoader* image = sAllImages[i+1];
        link(image, sEnv.DYLD_BIND_AT_LAUNCH, ImageLoader::RPathChain(NULL, NULL));
        // only INSERTED libraries can interpose
        image->registerInterposing();
    }
}

      



So no, only libraries inserted through DYLD_INSERT_LIBRARIES

apply interpolation.

+3


source







All Articles