Dylib基础

先掌握一些 macOS 下的前置知识:

otool查看装载指令

otool查看装载指令

LoadCommands基本的加载命令的数据结构如下:

struct load_command {
	uint32_t cmd;		/* type of load command  */
	uint32_t cmdsize;	/* total size of command in bytes */
};
...
struct dylib_command {
	uint32_t	cmd;		/* LC_ID_DYLIB, LC_LOAD_{,WEAK_}DYLIB,
					   LC_REEXPORT_DYLIB */
	uint32_t	cmdsize;	/* includes pathname string */
	struct dylib	dylib;		/* the library identification */
};
...
struct dylib {
    union lc_str  name;			/* library's path name */
    uint32_t timestamp;			/* library's build time stamp */
    uint32_t current_version;		/* library's current version number */
    uint32_t compatibility_version;	/* library's compatibility vers number*/
};

“DYLD_INSERT_LIBRARIES”环境变量

在 macOS 中动态链接器在程序加载之前加载 DYLD_INSERT_LIBRARIES 此环境变量中指定的任何动态库,本质上是将动态库注入应用程序。写个例子测试一下:

// clang -shared -framework Foundation example_dylib.m -o libexample.dylib
#import <Foundation/Foundation.h>
static void __attribute__((constructor)) initialize(void){
    NSLog(@"insert_dylib i'm here");
}
// clang -framework Foundation hello.m -o hello
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
    @autoreleasepool {
    NSLog(@"HelloWorld!");
    }
}

指定 libexample.dylib 并运行 $ DYLD_INSERT_LIBRARIES=./libexample.dylib ./hello libexample.dylib 被提前加载执行,运行结果如下:

$ DYLD_INSERT_LIBRARIES=./libexample.dylib ./hello                                           
2022-11-20 21:06:06.397 hello[17898:473695] insert_dylib i'm here
2022-11-20 21:06:06.398 hello[17898:473695] HelloWorld!

“DYLD_INSERT_LIBRARIES”的限制

Powered by Kali-Team