int main() { hash_djb_ctx_t ctx; hash_djb_init(&ctx); hash_djb_update(&ctx, "te", 2); hash_djb_update(&ctx, "st", 2); hash_djb_finish(&ctx); if (ctx.hash != 2087956275) return 1; hash_djb(&ctx, "test", 4); if (ctx.hash != 2087956275) return 2; hash_djb_init(&ctx); hash_djb_update(&ctx, "abcdefghij", 10); hash_djb_update(&ctx, "klmnopqrst", 10); hash_djb_update(&ctx, "uvwxyz", 6); hash_djb_finish(&ctx); if (ctx.hash != 3783864254) return 3; hash_djb(&ctx, "abcdefghijklmnopqrstuvwxyz", 26); if (ctx.hash != 3783864254) return 4; return 0; }
static int macho_parse(mach_header_t *mh, func_t *funcs) { int x,y; segment_command_t *seg; segment_command_t *seg_linkedit; segment_command_t *seg_text; symtab_command_t *sym; dylib_command_t *dlb; nlist_t *nls; char *strtab; // Sometimes, we can find our own image in memory, so unless we see a LC_ID_DYLIB // that matches our needed string, treat this as a failure int ret = 0; load_command_t *cmd = (load_command_t *)&mh[1]; for(x = 0; x < mh->ncmds; x++) { switch(cmd->cmd) { case LC_SEGMENT_64: case LC_SEGMENT: seg = (segment_command_t *)cmd; // __LINKEDIT if(hash_djb(seg->segname) == 0xc214bfb7) seg_linkedit = seg; // __TEXT if(hash_djb(seg->segname) == 0xec5f7168) seg_text = seg; break; case LC_ID_DYLIB: dlb = (dylib_command_t *)cmd; char *name = (char *)cmd + dlb->dylib.name.offset; // Is this the lib: /usr/lib/system/libdyld.dylib? if(hash_djb(name) == 0x8d3fccfd) ret = 1; break; case LC_SYMTAB: sym = (symtab_command_t *)cmd; // Determine symbol and string table offsets // http://lists.llvm.org/pipermail/lldb-commits/Week-of-Mon-20150608/019449.html strtab = (char *)mh + seg_linkedit->vmaddr + sym->stroff - seg_linkedit->fileoff - seg_text->vmaddr; nls = (nlist_t *)((char *)mh + seg_linkedit->vmaddr + sym->symoff - seg_linkedit->fileoff - seg_text->vmaddr); for(y = 0; y < sym->nsyms; y++) { char *sym_name = &strtab[nls[y].n_un.n_strx]; size_t sym_val = (size_t)((char *)mh + nls[y].n_value - seg_text->vmaddr); uint32_t hash = hash_djb(sym_name); switch(hash) { case 0x64c5cea0: funcs->NSCreateObjectFileImageFromMemory = (ptr_NSCreateObjectFileImageFromMemory) sym_val; break; case 0x6f320e79: funcs->NSLinkModule = (ptr_NSLinkModule) sym_val; break; case 0x515bc152: funcs->NSLookupSymbolInModule = (ptr_NSLookupSymbolInModule) sym_val; break; case 0xf4da6396: funcs->NSAddressOfSymbol = (ptr_NSAddressOfSymbol) sym_val; break; } } break; } cmd = (load_command_t *)((char *)cmd + cmd->cmdsize); } // We found libdyld.lib, and we are done return ret; }