From 852129aec7384293005e0280ce4cb6f92a5b5e52 Mon Sep 17 00:00:00 2001 From: nganhkhoa Date: Thu, 18 Feb 2021 10:42:34 +0700 Subject: [PATCH] add data --- data/Makefile | 16 + data/Makefile.common | 71 ++ data/README | 3 + data/binary.c | 111 ++ data/binary.h | 113 ++ data/cc.c | 271 ++++ data/cc.h | 6 + data/common.c | 181 +++ data/common.h | 80 ++ data/data | 1 + data/dyldcache/binary.c | 102 ++ data/dyldcache/binary.h | 20 + data/dyldcache/headers/dyld_cache_format.h | 52 + data/ent.plist | 3 + data/find.c | 480 +++++++ data/find.h | 31 + data/headers/machine.h | 344 +++++ data/ios-classify.h | 24 + data/ldid_wrapper | 22 + data/lzss.c | 99 ++ data/lzss.h | 3 + data/mach-o/binary.c | 474 +++++++ data/mach-o/binary.h | 76 ++ data/mach-o/headers/arm_reloc.h | 44 + data/mach-o/headers/fat.h | 63 + data/mach-o/headers/loader.h | 1340 ++++++++++++++++++++ data/mach-o/headers/nlist.h | 302 +++++ data/mach-o/headers/reloc.h | 202 +++ data/mach-o/headers/stab.h | 122 ++ data/mach-o/inject.c | 756 +++++++++++ data/mach-o/inject.h | 10 + data/mach-o/link.c | 466 +++++++ data/mach-o/link.h | 17 + data/mach-o/read_dyld_info.h | 56 + data/running_kernel.c | 353 ++++++ data/running_kernel.h | 19 + 36 files changed, 6333 insertions(+) create mode 100644 data/Makefile create mode 100644 data/Makefile.common create mode 100644 data/README create mode 100644 data/binary.c create mode 100644 data/binary.h create mode 100644 data/cc.c create mode 100644 data/cc.h create mode 100644 data/common.c create mode 100644 data/common.h create mode 120000 data/data create mode 100644 data/dyldcache/binary.c create mode 100644 data/dyldcache/binary.h create mode 100644 data/dyldcache/headers/dyld_cache_format.h create mode 100644 data/ent.plist create mode 100644 data/find.c create mode 100644 data/find.h create mode 100644 data/headers/machine.h create mode 100644 data/ios-classify.h create mode 100755 data/ldid_wrapper create mode 100644 data/lzss.c create mode 100644 data/lzss.h create mode 100644 data/mach-o/binary.c create mode 100644 data/mach-o/binary.h create mode 100644 data/mach-o/headers/arm_reloc.h create mode 100644 data/mach-o/headers/fat.h create mode 100644 data/mach-o/headers/loader.h create mode 100644 data/mach-o/headers/nlist.h create mode 100644 data/mach-o/headers/reloc.h create mode 100644 data/mach-o/headers/stab.h create mode 100644 data/mach-o/inject.c create mode 100644 data/mach-o/inject.h create mode 100644 data/mach-o/link.c create mode 100644 data/mach-o/link.h create mode 100644 data/mach-o/read_dyld_info.h create mode 100644 data/running_kernel.c create mode 100644 data/running_kernel.h diff --git a/data/Makefile b/data/Makefile new file mode 100644 index 0000000..126c192 --- /dev/null +++ b/data/Makefile @@ -0,0 +1,16 @@ +include Makefile.common +all: $(OUTDIR) $(OUTDIR)/libdata.a $(OUTDIR)/libdata.$(DYLIB) + +$(OUTDIR): + mkdir -p $(OUTDIR) $(OUTDIR)/mach-o $(OUTDIR)/dyldcache +clean: .clean + +OBJS := common.o binary.o running_kernel.o find.o cc.o lzss.o mach-o/binary.o mach-o/link.o mach-o/inject.o dyldcache/binary.o +OBJS := $(patsubst %,$(OUTDIR)/%,$(OBJS)) + +$(OUTDIR)/libdata.a: $(OBJS) + rm -f $@ + $(AR) rcs $@ $(OBJS) +$(OUTDIR)/libdata.$(DYLIB): $(OBJS) + $(GCC) $(DYNAMICLIB) -o $@ $(OBJS) + diff --git a/data/Makefile.common b/data/Makefile.common new file mode 100644 index 0000000..cf1f48a --- /dev/null +++ b/data/Makefile.common @@ -0,0 +1,71 @@ +BUILD ?= arm_universal +OUTDIR = $(BUILD) + +ifeq "$(wildcard /private)" "" +DYNAMICLIB = -shared +DYLIB = so +else +DYNAMICLIB = -dynamiclib -ldylib1.o +DYLIB = dylib +override CFLAGS += -DIMG3_SUPPORT +override LDFLAGS += -dead_strip +endif +override CFLAGS := -Os -Wall -Wextra -Wno-parentheses -Wreturn-type $(CFLAGS) +ifneq "$(NDEBUG)" "1" +override CFLAGS += -g3 +endif + +SDK_GCC = /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-gcc-4.2 -isysroot $(lastword $(wildcard /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS*.sdk)) -miphoneos-version-min=4.0 -mapcs-frame -fomit-frame-pointer -mthumb + +GCC_native = gcc +GCC_mp = gcc-mp-4.6 +GCC_universal = gcc -arch i386 -arch x86_64 +GCC_armv6 = $(SDK_GCC) -arch armv6 +GCC_armv7 = $(SDK_GCC) -arch armv7 +GCC_arm_universal = $(SDK_GCC) -arch armv6 -arch armv7 + +GXX_native = clang++ +GXX_mp = g++-mp-4.6 + +# C++ + +GXX ?= $(GXX_$(BUILD)) + +override CXXFLAGS += $(CFLAGS) -std=gnu++0x -Werror -Wno-pointer-arith +ifneq "$(GXX)" "" +override GXXO := $(GXX) $(CXXFLAGS) +override GXX := $(GXXO) $(LDFLAGS) +endif + +# C + +GCC ?= $(GCC_$(BUILD)) + +ifneq "$(findstring g++,$(GCC))" "" +override CFLAGS += -std=gnu++0x -fpermissive -Drestrict= +else +override CFLAGS += -std=gnu99 -Werror -Wimplicit -Wno-multichar +endif + +override GCCO := $(GCC) $(CFLAGS) +override GCC := $(GCCO) $(LDFLAGS) + +AR ?= ar +ifneq "$(filter $(BUILD),armv6 armv7 arm_universal)" "" +DATADIR = $(dir $(lastword $(MAKEFILE_LIST))) +LDID = $(DATADIR)/ldid_wrapper +else +LDID = +endif + +$(OUTDIR)/%.o: %.c *.h $(dir %)/*.h $(EXTRA_DEPS) + $(GCCO) -c -o $@ $< + +$(OUTDIR)/%.o: %.cpp *.h $(dir %)/*.h $(EXTRA_DEPS) + $(GXXO) -c -o $@ $< + +.clean: + rm -rf native universal armv6 armv7 arm_universal mp + +.data: + make -C $(DATA) BUILD=$(BUILD) diff --git a/data/README b/data/README new file mode 100644 index 0000000..053e97e --- /dev/null +++ b/data/README @@ -0,0 +1,3 @@ +This is used as a submodule by white (http://github.com/comex/white) and star (http://github.com/comex/starn). + +(What, you wanted to know what it does?) diff --git a/data/binary.c b/data/binary.c new file mode 100644 index 0000000..e3a0859 --- /dev/null +++ b/data/binary.c @@ -0,0 +1,111 @@ +#include "common.h" +#include "binary.h" +#include "find.h" +#include + +static inline bool prange_check(const struct binary *binary, prange_t range); + +void b_init(struct binary *binary) { + memset(binary, 0, sizeof(*binary)); +} + +static inline bool rangeconv_stuff(const struct binary *binary, addr_t addr, bool is_off, addr_t *out_address, addr_t *out_offset, size_t *out_size) { + uint32_t ls = binary->last_seg, ns = binary->nsegments, i = ls; + #define STUFF \ + const struct data_segment *seg = &binary->segments[i]; \ + addr_t diff = addr - (is_off ? seg->file_range : seg->vm_range).start; \ + if(diff < seg->file_range.size) { \ + ((struct binary *) binary)->last_seg = i; \ + *out_address = seg->vm_range.start + diff; \ + *out_offset = seg->file_range.start + diff; \ + *out_size = seg->file_range.size - diff; \ + return true; \ + } + STUFF + for(i = 0; i < ns; i++) { + STUFF + } + return false; +} + +inline prange_t rangeconv(range_t range, int flags) { + addr_t address; addr_t offset; size_t size; + if(rangeconv_stuff(range.binary, range.start, false, &address, &offset, &size)) { + if(__builtin_expect(flags & EXTEND_RANGE, 0)) { + range.size = size; + flags &= ~EXTEND_RANGE; + } + return rangeconv_off((range_t) {range.binary, offset, range.size}, flags); + } else if(flags & MUST_FIND) { + die("range (%08llx, %zx) not valid", (uint64_t) range.start, range.size); + } else { + return (prange_t) {NULL, 0}; + } +} + +inline prange_t rangeconv_off(range_t range, int flags) { + prange_t pr; + if(range.start == 0 && range.binary->header_offset) { + // dyld caches are weird. + range.start = range.binary->header_offset; + } + pr.start = (char *) range.binary->valid_range.start + range.start; + pr.size = range.size; + if(!prange_check(range.binary, pr)) { + if(flags & MUST_FIND) { + die("offset range (%08llx, %zx) not valid", (uint64_t) range.start, range.size); + } else { + return (prange_t) {NULL, 0}; + } + } + if(__builtin_expect(flags & EXTEND_RANGE, 0)) { + pr.size = ((char *) range.binary->valid_range.start + range.binary->valid_range.size - (char *) pr.start); + } + return pr; +} + +range_t range_to_off_range(range_t range, int flags) { + addr_t address; addr_t offset; size_t size; + if(rangeconv_stuff(range.binary, range.start, false, &address, &offset, &size) && range.size <= size) { + return (range_t) {range.binary, offset, range.size}; + } + if(flags & MUST_FIND) { + die("range (%08llx, %zx) not valid", (uint64_t) range.start, range.size); + } else { + return (range_t) {NULL, 0, 0}; + } +} + +range_t off_range_to_range(range_t range, int flags) { + addr_t address; addr_t offset; size_t size; + if(rangeconv_stuff(range.binary, range.start, true, &address, &offset, &size) && range.size <= size) { + return (range_t) {range.binary, address, range.size}; + } + if(flags & MUST_FIND) { + die("offset range (%08llx, %zx) not valid", (uint64_t) range.start, range.size); + } else { + return (range_t) {NULL, 0, 0}; + } +} + +addr_t b_sym(const struct binary *binary, const char *name, int options) { + addr_t result = binary->_sym ? binary->_sym(binary, name, options) : 0; + if(!result && (options & MUST_FIND)) { + die("symbol %s not found", name); + } + return result; +} + +void b_copy_syms(const struct binary *binary, struct data_sym **syms, uint32_t *nsyms, int options) { + if(!binary->_copy_syms) { + *syms = NULL; + *nsyms = 0; + return; + } + binary->_copy_syms(binary, syms, nsyms, options); +} + +void b_store(struct binary *binary, const char *path) { + store_file(binary->valid_range, path, 0755); +} + diff --git a/data/binary.h b/data/binary.h new file mode 100644 index 0000000..36934a9 --- /dev/null +++ b/data/binary.h @@ -0,0 +1,113 @@ +#pragma once +#include "common.h" +#include "headers/machine.h" + +// options +#define MUST_FIND 1 +// for sym +#define TO_EXECUTE 2 +#define PRIVATE_SYM 4 +#define IMPORTED_SYM 8 +// for rangeconv +#define EXTEND_RANGE 16 +// for find_string +#define PRECEDING_ZERO 32 +#define TRAILING_ZERO 64 + +struct dyld_cache_header; +struct shared_file_mapping_np; +struct mach_header; +struct dysymtab_command; + +struct data_segment { + range_t file_range; + range_t vm_range; + void *native_segment; +}; + +struct data_sym { + const char *name; + addr_t address; +}; + +struct binary { + bool valid; + + struct data_segment *segments; + uint32_t nsegments; + + cpu_type_t cpusubtype; + cpu_type_t cputype; + uint8_t pointer_size; + + prange_t valid_range; + size_t header_offset; + + uint32_t reserved[8]; + + uint32_t last_seg; + + struct binary *reexports; + unsigned int nreexports; + + struct mach_binary *mach; + struct dyldcache_binary *dyld; + + addr_t (*_sym)(const struct binary *binary, const char *name, int options); + void (*_copy_syms)(const struct binary *binary, struct data_sym **syms, uint32_t *nsyms, int options); +}; + +__BEGIN_DECLS + +static inline bool prange_check(const struct binary *binary, prange_t range) { + return binary->valid_range.start <= range.start && range.size <= (size_t) ((char *) binary->valid_range.start + binary->valid_range.size - (char *) range.start); +} + +__attribute__((pure)) prange_t rangeconv(range_t range, int flags); +__attribute__((pure)) prange_t rangeconv_off(range_t range, int flags); +__attribute__((pure)) range_t range_to_off_range(range_t range, int flags); +__attribute__((pure)) range_t off_range_to_range(range_t range, int flags); + +void b_init(struct binary *binary); + +// return value is |1 if to_execute is set and it is a thumb symbol +addr_t b_sym(const struct binary *binary, const char *name, int options); +void b_copy_syms(const struct binary *binary, struct data_sym **syms, uint32_t *nsyms, int options); + +void b_store(struct binary *binary, const char *path); +#define b_macho_store b_store + +static inline uint8_t b_pointer_size(const struct binary *binary) { + return sizeof(addr_t) == 4 ? 4 : binary->pointer_size; +} + +__attribute__((const)) +static inline addr_t read_pointer(const void *ptr, int pointer_size) { + if(pointer_size == 4) { + return *((uint32_t *) ptr); + } else { + return *((uint64_t *) ptr); + } +} + +static inline void write_pointer(void *ptr, addr_t value, int pointer_size) { + if(pointer_size == 4) { + *((uint32_t *) ptr) = value; + } else { + *((uint64_t *) ptr) = value; + } +} + +__END_DECLS + +// b_read32, etc. +#define r(sz) \ +static inline uint##sz##_t b_read##sz(const struct binary *binary, addr_t addr) { \ + return *(uint##sz##_t *)(rangeconv((range_t) {binary, addr, sz/8}, MUST_FIND).start); \ +} + +r(8) +r(16) +r(32) +r(64) + diff --git a/data/cc.c b/data/cc.c new file mode 100644 index 0000000..c878bd7 --- /dev/null +++ b/data/cc.c @@ -0,0 +1,271 @@ +#ifdef IMG3_SUPPORT +#include +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "lzss.h" + +// this is sort of irrelevant, but I'd like to use it for OS X kernelcaches which are sometimes compressed within fat + +#ifndef __arm__ // copy and paste from libstuff +static const struct arch_flag { + const char *name; + cpu_type_t type; + cpu_subtype_t subtype; +} arch_flags[] = { + { "any", CPU_TYPE_ANY, CPU_SUBTYPE_MULTIPLE }, + { "little", CPU_TYPE_ANY, CPU_SUBTYPE_LITTLE_ENDIAN }, + { "big", CPU_TYPE_ANY, CPU_SUBTYPE_BIG_ENDIAN }, + +/* 64-bit Mach-O architectures */ + + /* architecture families */ + { "ppc64", CPU_TYPE_POWERPC64, CPU_SUBTYPE_POWERPC_ALL }, + { "x86_64", CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL }, + /* specific architecture implementations */ + { "ppc970-64", CPU_TYPE_POWERPC64, CPU_SUBTYPE_POWERPC_970 }, + +/* 32-bit Mach-O architectures */ + + /* architecture families */ + { "ppc", CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL }, + { "i386", CPU_TYPE_I386, CPU_SUBTYPE_I386_ALL }, + { "m68k", CPU_TYPE_MC680x0, CPU_SUBTYPE_MC680x0_ALL }, + { "hppa", CPU_TYPE_HPPA, CPU_SUBTYPE_HPPA_ALL }, + { "sparc", CPU_TYPE_SPARC, CPU_SUBTYPE_SPARC_ALL }, + { "m88k", CPU_TYPE_MC88000, CPU_SUBTYPE_MC88000_ALL }, + { "i860", CPU_TYPE_I860, CPU_SUBTYPE_I860_ALL }, + { "arm", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_ALL }, + /* specific architecture implementations */ + { "ppc601", CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_601 }, + { "ppc603", CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_603 }, + { "ppc603e",CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_603e }, + { "ppc603ev",CPU_TYPE_POWERPC,CPU_SUBTYPE_POWERPC_603ev }, + { "ppc604", CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_604 }, + { "ppc604e",CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_604e }, + { "ppc750", CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_750 }, + { "ppc7400",CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_7400 }, + { "ppc7450",CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_7450 }, + { "ppc970", CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_970 }, + { "i486", CPU_TYPE_I386, CPU_SUBTYPE_486 }, + { "i486SX", CPU_TYPE_I386, CPU_SUBTYPE_486SX }, + { "pentium",CPU_TYPE_I386, CPU_SUBTYPE_PENT }, /* same as i586 */ + { "i586", CPU_TYPE_I386, CPU_SUBTYPE_586 }, + { "pentpro", CPU_TYPE_I386, CPU_SUBTYPE_PENTPRO }, /* same as i686 */ + { "i686", CPU_TYPE_I386, CPU_SUBTYPE_PENTPRO }, + { "pentIIm3",CPU_TYPE_I386, CPU_SUBTYPE_PENTII_M3 }, + { "pentIIm5",CPU_TYPE_I386, CPU_SUBTYPE_PENTII_M5 }, + { "pentium4",CPU_TYPE_I386, CPU_SUBTYPE_PENTIUM_4 }, + { "m68030", CPU_TYPE_MC680x0, CPU_SUBTYPE_MC68030_ONLY }, + { "m68040", CPU_TYPE_MC680x0, CPU_SUBTYPE_MC68040 }, + { "hppa7100LC", CPU_TYPE_HPPA, CPU_SUBTYPE_HPPA_7100LC }, + { "armv4t", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V4T}, + { "armv5", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V5TEJ}, + { "xscale", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_XSCALE}, + { "armv6", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 }, + { "armv7", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 }, + { NULL, 0, 0 } +}; +#endif + +static prange_t parse_fat(prange_t input, const char *arch) { +#ifdef __arm__ + (void) arch; + return input; +#else + if(input.size < sizeof(struct fat_header)) return input; + struct fat_header *fh = input.start; + if(SWAP32(fh->magic) != FAT_MAGIC) return input; + if(!arch) die("arch not specified for fat file"); + + cpu_type_t type; + cpu_subtype_t subtype; + for(const struct arch_flag *p = arch_flags; p < (struct arch_flag *) (&arch_flags + 1); p++) { + if(!strcmp(arch, p->name)) { + type = p->type; + subtype = p->subtype; + goto ok; + } + } + die("unknown arch %s", arch); + + ok:; + struct fat_arch *fa = (void *) (fh + 1); + uint32_t nfat_arch = SWAP32(fh->nfat_arch); + if((input.size - sizeof(struct fat_header)) / sizeof(struct fat_arch) < nfat_arch) die("nfat_arch overflow"); + for(uint32_t i = 0; i < nfat_arch; i++) { + cpu_type_t mytype = SWAP32(fa[i].cputype); + cpu_subtype_t mysubtype = SWAP32(fa[i].cpusubtype); + uint32_t offset = SWAP32(fa[i].offset); + uint32_t size = SWAP32(fa[i].size); + if(type == mytype && subtype == mysubtype) { + if(offset > input.size || size > input.size - offset) die("fat overflow"); + return (prange_t) {input.start + offset, size}; + } + } + die("arch %s not present in fat file", arch); +#endif +} + +static prange_t decrypt(uint32_t key_bits, prange_t key, prange_t iv, prange_t buffer) { + size_t size; + switch(key_bits) { + case 128: size = kCCKeySizeAES128; break; + case 192: size = kCCKeySizeAES192; break; + case 256: size = kCCKeySizeAES256; break; + default: abort(); + } + if(key.size != size) { + die("bad key_len %zu", key.size); + } + if(iv.size != 16) { + die("bad iv_len %zu", iv.size); + } + size_t outbuf_len = buffer.size + 32; + autofree void *outbuf = malloc(outbuf_len); + assert(outbuf); + CCCryptorStatus result = CCCrypt(kCCDecrypt, + kCCAlgorithmAES128, + 0, + key.start, + size, + iv.start, + buffer.start, + buffer.size & ~0xf, + outbuf, + outbuf_len, + &outbuf_len); + + if(result != kCCSuccess) { + die("decryption failed: %d", (unsigned int) result); + } + return (prange_t) {outbuf, outbuf_len}; +} + +struct comp_header { + uint32_t signature; + uint32_t compression_type; + uint32_t checksum; + uint32_t length_uncompressed; + uint32_t length_compressed; + uint8_t padding[0x16C]; +} __attribute__((packed)); + +static prange_t decompress(prange_t buffer) { + // is it really compressed? + if(buffer.size < sizeof(struct comp_header)) return buffer; + struct comp_header *ch = buffer.start; + if(!(ch->signature == 0x706d6f63 && ch->compression_type == 0x73737a6c)) { + return buffer; + } + + uint32_t length_compressed = swap32(ch->length_compressed); + uint32_t length_uncompressed = swap32(ch->length_uncompressed); + uint32_t checksum = swap32(ch->checksum); + if((buffer.size - sizeof(struct comp_header)) < length_compressed) { + die("too large length_compressed %x > %lx", length_compressed, buffer.size - sizeof(struct comp_header)); + } + // not a fan of buffer overflows + size_t decbuf_len = (length_uncompressed + 0x1fff) & ~0xfff; + void *decbuf = mmap(NULL, decbuf_len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0); + assert(decbuf != MAP_FAILED); + assert(!mprotect((char *)decbuf + decbuf_len - 0x1000, PROT_NONE, 0x1000)); + + int actual_length_uncompressed = decompress_lzss(decbuf, (void *) (ch + 1), length_compressed); + if(actual_length_uncompressed < 0 || (unsigned int) actual_length_uncompressed != length_uncompressed) { + die("invalid complzss thing"); + } + +#ifndef __arm__ + uint32_t actual_checksum = lzadler32(decbuf, actual_length_uncompressed); + if(actual_checksum != checksum) { + die("bad checksum (%x, %x)", actual_checksum, checksum); + } +#else + (void) checksum; +#endif + return (prange_t) {decbuf, actual_length_uncompressed}; +} + +struct img3_header { + uint32_t magic; + uint32_t size; + uint32_t data_size; + uint32_t shsh_offset; + uint32_t name; +} __attribute__((packed)); + +struct img3_tag { + uint32_t magic; + uint32_t size; + uint32_t data_size; + char data[0]; + union { + struct { + uint32_t key_modifier; + uint32_t key_bits; + } __attribute__((packed)) kbag; + }; +} __attribute__((packed)); + +static prange_t parse_img3(prange_t img3, const char *key, const char *iv) { + if(img3.size < sizeof(struct img3_header)) return img3; + struct img3_header *hdr = img3.start; + if(hdr->magic != (uint32_t) 'Img3') return img3; + + assert(hdr->size <= img3.size); + void *end = (char *)(img3.start) + hdr->size; + //assert(hdr->name == (uint32_t) 'krnl'); + struct img3_tag *tag = (void *) (hdr + 1); + struct img3_tag *tag2; + prange_t result; + memset(&result, 0, sizeof(result)); // not actually necessary, >:( gcc + bool have_data = false, have_kbag = false; + uint32_t key_bits = 0; + while(!(have_data && have_kbag)) { + if((void *)tag->data >= end) { + // out of tags + break; + } + //printf("%.4s %p %x\n", (char *) &tag->magic, &tag->data[0], tag->data_size); + tag2 = (void *) ((char *)tag + tag->size); + if((void *)tag2 > end || tag2 <= tag) { + die("tag cut off"); + } + if(tag->magic == (uint32_t) 'DATA') { + result = (prange_t) {tag->data, tag->size - 3 * sizeof(uint32_t)}; + have_data = true; + } else if(tag->magic == (uint32_t) 'KBAG') { + assert(tag->size >= 5 * sizeof(uint32_t)); + if(tag->kbag.key_modifier) { + key_bits = tag->kbag.key_bits; + have_kbag = true; + } + } + tag = tag2; + } + + if(!have_data) { + die("didn't find DATA"); + } + + if(have_kbag) { + if(!key || !iv) die("key/iv not specified for encrypted img3"); + return decrypt(key_bits, parse_hex_string(key), parse_hex_string(iv), result); + } else { + // unencrypted like iOS 4.3.1 + return result; + } +} + +prange_t unpack(prange_t input, const char *key, const char *iv) { + input = parse_img3(input, key, iv); + input = parse_fat(input, key); + input = decompress(input); + return input; +} +#endif diff --git a/data/cc.h b/data/cc.h new file mode 100644 index 0000000..66a2226 --- /dev/null +++ b/data/cc.h @@ -0,0 +1,6 @@ +#include "common.h" +__BEGIN_DECLS +#ifdef IMG3_SUPPORT +prange_t unpack(prange_t input, const char *key, const char *iv); +#endif +__END_DECLS diff --git a/data/common.c b/data/common.c new file mode 100644 index 0000000..8c4b0e5 --- /dev/null +++ b/data/common.c @@ -0,0 +1,181 @@ +#include "common.h" +#include +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#endif + +prange_t pdup(prange_t range, size_t newsize, size_t offset) { + if(newsize < offset + range.size) { + die("pdup: newsize=%zu < offset=%zu + range.size=%zu", newsize, offset, range.size); + } + void *buf = mmap(NULL, newsize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + if(buf == MAP_FAILED) { + edie("pdup: could not mmap"); + } +#ifdef __APPLE__ + munmap(buf + offset, range.size); + vm_prot_t cur, max; + vm_address_t addr = (vm_address_t) (buf + offset); + kern_return_t kr = vm_remap(mach_task_self(), &addr, range.size, 0xfff, 0, mach_task_self(), (vm_address_t) range.start, true, &cur, &max, VM_INHERIT_NONE); + if(kr) { + die("pdup: kr = %d", (int) kr); + } +#else + memcpy(buf + offset, range.start, range.size); +#endif + return (prange_t) {buf, newsize}; +} + +bool is_valid_range(prange_t range) { + char c; + return !mincore(range.start, range.size, (void *) &c); +} + +static inline uint8_t parse_hex_digit(char digit, const char *string) { + switch(digit) { + case '0' ... '9': + return (uint8_t) (digit - '0'); + case 'a' ... 'f': + return (uint8_t) (10 + (digit - 'a')); + default: + die("bad hex string %s", string); + } +} + +prange_t parse_hex_string(const char *string) { + if(string[0] == '0' && string[1] == 'x') { + string += 2; + } + const char *in = string; + size_t len = strlen(string); + size_t out_len = (len + 1)/2; + uint8_t *out = malloc(out_len); + prange_t result = (prange_t) {out, out_len}; + if(len % 2) { + *out++ = parse_hex_digit(*in++, string); + } + while(out_len--) { + uint8_t a = parse_hex_digit(*in++, string); + uint8_t b = parse_hex_digit(*in++, string); + *out++ = (uint8_t) ((a * 0x10) + b); + } + return result; +} + +addr_t parse_hex_addr(const char *string) { + char *end; + addr_t result = (addr_t) strtoll(string, &end, 16); + if(!*string || *end) { + die("invalid hex value %s", string); + } + return result; +} + +prange_t load_file(const char *filename, bool rw, mode_t *mode) { +#define _arg filename + int fd = open(filename, O_RDONLY); + if(fd == -1) { + edie("could not open"); + } + if(mode) { + struct stat st; + if(fstat(fd, &st)) { + edie("could not lstat"); + } + *mode = st.st_mode; + } + prange_t ret = load_fd(fd, rw); + close(fd); + return ret; +#undef _arg +} + +prange_t load_fd(int fd, bool rw) { + off_t end = lseek(fd, 0, SEEK_END); + if(end == 0) { + fprintf(stderr, "load_fd: warning: mapping an empty file\n"); + } + if(sizeof(off_t) > sizeof(size_t) && end > (off_t) SIZE_MAX) { + die("too big: %lld", (long long) end); + } + void *buf = mmap(NULL, (size_t) end, PROT_READ | (rw ? PROT_WRITE : 0), MAP_PRIVATE, fd, 0); + if(buf == MAP_FAILED) { + edie("could not mmap buf (end=%zu)", (size_t) end); + } + return (prange_t) {buf, (size_t) end}; +} + +void store_file(prange_t range, const char *filename, mode_t mode) { +#define _arg filename + int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, mode); + if(fd == -1) { + edie("could not open"); + } + if(write(fd, range.start, range.size) != (ssize_t) range.size) { + edie("could not write data"); + } + close(fd); +#undef _arg +} + +#if defined(__GNUC__) && !defined(__clang__) && !defined(__arm__) +#define EXCEPTION_SUPPORT 1 +#endif + +// Basically, ctypes/libffi is very fancy but does not support using setjmp() as an exception mechanism. Running setjmp() directly from Python is... not effective, as you might expect. So here's an unnecessarily portable hack. + +#ifdef EXCEPTION_SUPPORT +#include +#include + +static bool call_going; +static void *call_func; +static jmp_buf call_jmp; +static char call_error[256]; + +void data_call_init(void *func) { + call_func = func; + call_going = true; + call_error[0] = 0; +} + +void data_call(__unused int whatever, ...) { + if(!setjmp(call_jmp)) { + __builtin_return(__builtin_apply(call_func, __builtin_apply_args(), 32)); + } +} + +char *data_call_fini() { + call_going = false; + return call_error; +} + +void _die(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + + if(call_going) { + vsnprintf(call_error, sizeof(call_error), fmt, ap); + longjmp(call_jmp, -1); + } else { + vfprintf(stderr, fmt, ap); + abort(); + } + + va_end(ap); +} + +#else +void _die(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + abort(); + va_end(ap); +} +#endif + diff --git a/data/common.h b/data/common.h new file mode 100644 index 0000000..4b8a8dd --- /dev/null +++ b/data/common.h @@ -0,0 +1,80 @@ +#pragma once +#define _XOPEN_SOURCE 500 +#define _BSD_SOURCE +#define _DARWIN_C_SOURCE + +//#define PROFILING + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef PROFILING +#include +#endif + +#define swap32 __builtin_bswap32 +#define SWAP32(x) ((typeof(x)) swap32((uint32_t) (x))) + +// this function gets rid of compiler warnings about "comparison always true" - if that is true (because size_t is 64-bit on this architecture), great, don't bother me about it +__attribute__((always_inline)) static inline size_t _id(size_t x) { return x; } +#define MAX_ARRAY(typ) _id(~(size_t)0 / sizeof(typ)) + + +static inline void _free_cleanup(void *pp) { + void *p = *((void **) pp); + if(p) free(p); +} +#define autofree __attribute__((cleanup(_free_cleanup))) + +__unused static const char *const _arg = (char *) MAP_FAILED; + +#define die(fmt, args...) ((_arg == MAP_FAILED) ? \ + _die("%s: " fmt "\n", __func__, ##args) : \ + _die("%s: %s: " fmt "\n", __func__, _arg, ##args)) + +#define edie(fmt, args...) die(fmt ": %s", ##args, strerror(errno)) + +struct binary; +#define ADDR64 1 +#if ADDR64 +typedef uint64_t addr_t; +#else +typedef uint32_t addr_t; +#endif +typedef struct { const struct binary *binary; addr_t start; size_t size; } range_t; +typedef struct { addr_t start; size_t size; } arange_t; +typedef struct { void *start; size_t size; } prange_t; + +__BEGIN_DECLS + +prange_t pdup(prange_t range, size_t newsize, size_t offset); + +bool is_valid_range(prange_t range); + +prange_t parse_hex_string(const char *string); + +prange_t load_file(const char *filename, bool rw, mode_t *mode); +prange_t load_fd(int fd, bool rw); + +void store_file(prange_t range, const char *filename, mode_t mode); + +addr_t parse_hex_addr(const char *string); + +__attribute__((noreturn, format(printf, 1, 2))) +void _die(const char *fmt, ...); + +#if defined(__APPLE__) && __DARWIN_C_LEVEL < 200809L +static inline size_t strnlen(const char *s, size_t n) { + const char *p = (const char *) memchr(s, 0, n); + return p ? (size_t) (p-s) : n; +} +#endif + +__END_DECLS diff --git a/data/data b/data/data new file mode 120000 index 0000000..945c9b4 --- /dev/null +++ b/data/data @@ -0,0 +1 @@ +. \ No newline at end of file diff --git a/data/dyldcache/binary.c b/data/dyldcache/binary.c new file mode 100644 index 0000000..95a5b49 --- /dev/null +++ b/data/dyldcache/binary.c @@ -0,0 +1,102 @@ +#include "binary.h" +#include "../mach-o/headers/loader.h" +#include "headers/dyld_cache_format.h" + +#define downcast(val, typ) ({ typeof(val) v = (val); typ t = (typ) v; if(t != v) die("out of range %s", #val); t; }) + +void b_prange_load_dyldcache(struct binary *binary, prange_t pr, const char *name) { +#define _arg name + + binary->valid = true; + binary->pointer_size = 4; + binary->dyld = calloc(1, sizeof(*binary->dyld)); + binary->valid_range = pr; + + if(pr.size < sizeof(*binary->dyld->hdr)) { + die("truncated (no room for dyld cache header)"); + } + binary->dyld->hdr = pr.start; + + if(memcmp(binary->dyld->hdr->magic, "dyld_", 5)) { + die("not a dyld cache"); + } + char *thing = binary->dyld->hdr->magic + sizeof(binary->dyld->hdr->magic) - 7; + if(!memcmp(thing, " armv7", 7)) { + binary->cputype = CPU_TYPE_ARM; + binary->cpusubtype = CPU_SUBTYPE_ARM_V7; + } else if(!memcmp(thing, " armv6", 7)) { + binary->cputype = CPU_TYPE_ARM; + binary->cpusubtype = CPU_SUBTYPE_ARM_V6; + } else { + die("unknown processor in magic: %.6s", thing); + } + + if(binary->dyld->hdr->mappingCount > 1000) { + die("insane mapping count: %u", binary->dyld->hdr->mappingCount); + } + binary->nsegments = binary->dyld->hdr->mappingCount; + binary->segments = malloc(sizeof(*binary->segments) * binary->nsegments); + struct shared_file_mapping_np *mappings = rangeconv_off((range_t) {binary, binary->dyld->hdr->mappingOffset, binary->dyld->hdr->mappingCount * sizeof(struct shared_file_mapping_np)}, MUST_FIND).start; + for(uint32_t i = 0; i < binary->dyld->hdr->mappingCount; i++) { + struct data_segment *seg = &binary->segments[i]; + seg->vm_range.binary = seg->file_range.binary = binary; + seg->native_segment = &mappings[i]; + seg->vm_range.start = downcast(mappings[i].sfm_address, addr_t); + seg->file_range.start = downcast(mappings[i].sfm_file_offset, addr_t); + seg->file_range.size = seg->vm_range.size = downcast(mappings[i].sfm_size, size_t); + } + + + for(unsigned int i = 0; i < binary->dyld->nmappings; i++) { + struct shared_file_mapping_np *mapping = &binary->dyld->mappings[i]; + if(mapping->sfm_file_offset >= pr.size || mapping->sfm_size > pr.size - mapping->sfm_file_offset) { + die("truncated (no room for dyld cache mapping %d)", i); + } + } +#undef _arg +} + +void b_dyldcache_load_macho(const struct binary *binary, const char *filename, struct binary *out) { + if(binary == out) { + die("uck"); + } + + if(binary->dyld->hdr->imagesCount > 1000) { + die("insane images count"); + } + + struct dyld_cache_image_info *info = rangeconv_off((range_t) {binary, binary->dyld->hdr->imagesOffset, binary->dyld->hdr->imagesCount * sizeof(*info)}, MUST_FIND).start; + for(unsigned int i = 0; i < binary->dyld->hdr->imagesCount; i++) { + char *name = rangeconv_off((range_t) {binary, info[i].pathFileOffset, 128}, MUST_FIND).start; + + if(strncmp(name, filename, 128)) { + continue; + } + // we found it + b_prange_load_macho(out, binary->valid_range,range_to_off_range((range_t) {binary, (uint32_t) info[i].address, 0}, MUST_FIND).start, filename); + + // look for reexports (maybe blowing the stack) + int count = 0; + CMD_ITERATE(b_mach_hdr(out), cmd) { + if(cmd->cmd == LC_REEXPORT_DYLIB) count++; + } + if(count > 0 && count < 1000) { + out->nreexports = (unsigned int) count; + struct binary *p = out->reexports = malloc(out->nreexports * sizeof(struct binary)); + CMD_ITERATE(b_mach_hdr(out), cmd) { + if(cmd->cmd == LC_REEXPORT_DYLIB) { + const char *name = convert_lc_str(cmd, ((struct dylib_command *) cmd)->dylib.name.offset); + b_dyldcache_load_macho(binary, name, p); + p++; + } + } + } + + return; + } + die("couldn't find %s in dyld cache", filename); +} + +void b_load_dyldcache(struct binary *binary, const char *filename) { + return b_prange_load_dyldcache(binary, load_file(filename, true, NULL), filename); +} diff --git a/data/dyldcache/binary.h b/data/dyldcache/binary.h new file mode 100644 index 0000000..b8b0fc1 --- /dev/null +++ b/data/dyldcache/binary.h @@ -0,0 +1,20 @@ +#pragma once +#include "../binary.h" +#include "../mach-o/binary.h" + +struct dyldcache_binary { + struct dyld_cache_header *hdr; + struct shared_file_mapping_np *mappings; + uint32_t nmappings; + struct shared_file_mapping_np *last_sfm; +}; + +__BEGIN_DECLS + +void b_prange_load_dyldcache(struct binary *binary, prange_t range, const char *name); +void b_dyldcache_load_macho(const struct binary *binary, const char *filename, struct binary *out); + +void b_load_dyldcache(struct binary *binary, const char *filename); + + +__END_DECLS diff --git a/data/dyldcache/headers/dyld_cache_format.h b/data/dyldcache/headers/dyld_cache_format.h new file mode 100644 index 0000000..a611d02 --- /dev/null +++ b/data/dyldcache/headers/dyld_cache_format.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ + +struct shared_file_mapping_np { + uint64_t sfm_address; + uint64_t sfm_size; + uint64_t sfm_file_offset; + int sfm_max_prot; + int sfm_init_prot; +}; + +// v1 apparently has some extra gunk at the end, oh well +struct dyld_cache_header +{ + char magic[16]; // e.g. "dyld_v0 ppc" + uint32_t mappingOffset; // file offset to first shared_file_mapping_np + uint32_t mappingCount; // number of shared_file_mapping_np entries + uint32_t imagesOffset; // file offset to first dyld_cache_image_info + uint32_t imagesCount; // number of dyld_cache_image_info entries + uint64_t dyldBaseAddress; // base address of dyld when cache was built +}; + +struct dyld_cache_image_info +{ + uint64_t address; + uint64_t modTime; + uint64_t inode; + uint32_t pathFileOffset; + uint32_t pad; +}; + + diff --git a/data/ent.plist b/data/ent.plist new file mode 100644 index 0000000..fc75011 --- /dev/null +++ b/data/ent.plist @@ -0,0 +1,3 @@ + + +get-task-allowrun-unsigned-codetask_for_pid-allow diff --git a/data/find.c b/data/find.c new file mode 100644 index 0000000..1953110 --- /dev/null +++ b/data/find.c @@ -0,0 +1,480 @@ +#include "find.h" +#include "binary.h" + +// Various links: +// http://ridiculousfish.com/blog/archives/2006/05/30/old-age-and-treachery/ +// http://www-igm.univ-mlv.fr/~lecroq/string/tunedbm.html#SECTION00195 +// http://www-igm.univ-mlv.fr/~lecroq/string/node19.html#SECTION00190 (was using this) + +static addr_t find_data_raw(range_t range, int16_t *buf, ssize_t pattern_size, size_t offset, int align, int options, const char *name) { + int8_t ps = (int8_t) pattern_size; + if(ps != pattern_size) { + die("pattern too long"); + } + // the problem with this is that it is faster to search for everything at once + + // reduce inefficiency + for(int pos = pattern_size - 1; pos >= 0; pos--) { + if(buf[pos] == -1) { + pattern_size--; + } else { + break; + } + } + int8_t table[256]; + for(int c = 0; c < 256; c++) { + table[c] = ps; + } + for(int8_t pos = 0; pos < ps - 1; pos++) { + if(buf[pos] == -1) { + // Unfortunately, we can't put any character past being in this position... + for(int i = 0; i < 256; i++) { + table[i] = ps - pos - 1; + } + } else { + table[buf[pos]] = ps - pos - 1; + } + } + + // this can't be -1 due to above + int8_t shift = table[buf[pattern_size - 1]]; + table[buf[pattern_size - 1]] = 0; + + // now, for each c, let x be the last position in the string, other than the final position, where c might appear, or -1 if it doesn't appear anywhere; table[i] is size - x - 1. + // so if we got c but no match, we can skip ahead by table[i] + // updated + buf += pattern_size - 1; + addr_t foundit = 0; + prange_t pr = rangeconv(range, MUST_FIND); + uint8_t *start = pr.start + pattern_size - 1; + uint8_t *end = pr.start + pr.size; + uint8_t *cutoff = end - 400; // arbitrary + uint8_t *cursor = start; + +#define GUTS(keep_going) \ + { \ + for(int i = 0; i >= (-pattern_size + 1); i--) { \ + if(buf[i] != -1 && cursor[i] != buf[i]) { \ + /* Not a match */ \ + goto keep_going; \ + } \ + } \ + /* Whoa, we found it */ \ + addr_t new_match = cursor - start + range.start; \ + if(align && (new_match & (align - 1))) { \ + /* Just kidding. */ \ + goto keep_going; \ + } \ + if(foundit) { \ + die("found [%s] multiple times in range: first at %08llx then at %08llx", name, (uint64_t) foundit, (uint64_t) new_match); \ + } \ + foundit = new_match; \ + if(align) { \ + goto done; \ + } \ + } \ + /* otherwise, keep searching to make sure we won't find it again */ \ + keep_going: \ + cursor += shift; + + uint8_t jump; + + while(1) { + if(cursor >= cutoff) break; + do { + jump = table[*cursor]; + cursor += jump; + jump = table[*cursor]; + cursor += jump; + jump = table[*cursor]; + cursor += jump; + if(cursor >= end) goto done; + } while(jump); + GUTS(lbl1) + } + if(cursor >= end) goto done; + while(1) { + do { + jump = table[*cursor]; + cursor += jump; + if(cursor >= end) goto done; + } while(jump); + GUTS(lbl2) + } + done: + if(foundit) { + return foundit + offset; + } else if(options & MUST_FIND) { + die("didn't find [%s] in range (%08llx, %zx)", name, (uint64_t) range.start, range.size); + } else { + return 0; + } +} + +static void parse_pattern(const char *to_find, int16_t buf[128], ssize_t *pattern_size, ssize_t *offset) { + *pattern_size = 0; + *offset = 0; + autofree char *to_find_ = strdup(to_find); + while(to_find_) { + char *bit = strsep(&to_find_, " "); + if(!strcmp(bit, "-")) { + *offset = *pattern_size; + continue; + } else if(!strcmp(bit, "+")) { + *offset = *pattern_size + 1; + continue; + } else if(!strcmp(bit, "..")) { + buf[*pattern_size] = -1; + } else { + char *endptr; + buf[*pattern_size] = (int16_t) (strtol(bit, &endptr, 16) & 0xff); + if(*endptr) { + die("invalid bit %s in [%s]", bit, to_find); + } + } + if(++*pattern_size >= 128) { + die("pattern [%s] too big", to_find); + } + } +} + +addr_t find_data(range_t range, const char *to_find, int align, int options) { + int16_t buf[128]; + ssize_t pattern_size, offset; + parse_pattern(to_find, buf, &pattern_size, &offset); + return find_data_raw(range, buf, pattern_size, offset, align, options, to_find); +} + +addr_t find_string(range_t range, const char *string, int align, int options) { + size_t len = strlen(string); + autofree int16_t *buf = malloc(sizeof(int16_t) * (len + 2)); + buf[0] = buf[len + 1] = 0; + for(unsigned int i = 0; i < len; i++) { + buf[i+1] = (uint8_t) string[i]; + } + bool pz = options & PRECEDING_ZERO; + bool tz = options & TRAILING_ZERO; + addr_t result = find_data_raw(range, pz ? buf : buf + 1, len + tz + pz, pz ? 1 : 0, align, options, string); + return result; +} + +addr_t find_bytes(range_t range, const char *bytes, size_t len, int align, int options) { + autofree int16_t *buf = malloc(sizeof(int16_t) * (len + 2)); + for(unsigned int i = 0; i < len; i++) { + buf[i] = (uint8_t) bytes[i]; + } + addr_t result = find_data_raw(range, buf, len, 0, align, options, "bytes"); + return result; +} +addr_t find_int32(range_t range, uint32_t number, int options) { + prange_t pr = rangeconv(range, MUST_FIND); + char *start = pr.start; + char *end = pr.start + pr.size; + for(char *p = start; p + 4 <= end; p++) { + if(*((uint32_t *)p) == number) { + return p - start + range.start; + } + } + if(options & MUST_FIND) { + die("didn't find %08x in range", number); + } else { + return 0; + } +} + +// search for push {..., lr}; add r7, sp, ... +// if is_thumb = 2, then search for both thumb and arm variants +addr_t find_bof(range_t range, addr_t eof, int is_thumb) { + addr_t start = eof & ~1; + if(start - range.start >= range.size) { + die("out of range: %llx", (uint64_t) eof); + } + + uint8_t *p = rangeconv(range, MUST_FIND).start + (start - range.start); + addr_t addr = start; + if(addr & 1) { p--; addr--; } + for(p -= 8, addr -= 8; addr >= start - 0x1000 && addr >= range.start; p -= 2, addr -= 2) { + if(p[1] == 0xb5 && p[3] == 0xaf && is_thumb != 0) { + return addr | 1; + } else if(p[2] == 0x2d && p[3] == 0xe9 && + p[6] == 0x8d && p[7] == 0xe2 && + is_thumb != 1 && !(addr & 2)) { + return addr; + } + + } + die("couldn't find the beginning of %08llx", (uint64_t) eof); +} + +uint32_t resolve_ldr(const struct binary *binary, addr_t addr) { + uint32_t val = b_read32(binary, addr & ~1); + addr_t target; + if(addr & 1) { + addr_t base = ((addr + 3) & ~3); + if((val & 0xf800) == 0x4800) { // thumb + target = base + ((val & 0xff) * 4); + } else if((val & 0xffff) == 0xf8df) { // thumb-2 + target = base + ((val & 0x0fff0000) >> 16); + } else { + die("weird thumb instruction %08x at %08llx", val, (uint64_t) addr); + } + } else { + addr_t base = addr + 8; + if((val & 0x0fff0000) == 0x59f0000) { // arm + target = base + (val & 0xfff); + } else { + die("weird ARM instruction %08x at %08llx", val, (uint64_t) addr); + } + } + return b_read32(binary, target); +} + +addr_t find_bl(range_t *range) { + bool thumb = range->start & 1; + range->start &= ~1; + prange_t pr = rangeconv(*range, MUST_FIND); + uint32_t diff; + void *base; + if(thumb) { + uint16_t *p = pr.start; + while((uintptr_t)(p + 2) <= (uintptr_t)pr.start + pr.size) { + base = p; + uint16_t val = *p++; + if((val & 0xf800) == 0xf000) { + uint32_t imm10 = val & 0x3ff; + uint32_t S = ((val & 0x400) >> 10); + uint16_t val2 = *p++; + + uint32_t J1 = ((val2 & 0x2000) >> 13); + uint32_t J2 = ((val2 & 0x800) >> 11); + uint32_t I1 = ~(J1 ^ S) & 1, I2 = ~(J2 ^ S) & 1; + uint32_t imm11 = val2 & 0x7ff; + diff = (S << 24) | (I1 << 23) | (I2 << 22) | (imm10 << 12) | (imm11 << 1); + + if((val2 & 0xd000) == 0xd000) { + // BL + diff |= 1; + goto ok; + } else if((val2 & 0xd000) == 0xc000) { + // BLX + goto ok; + } + } + } + } else { + uint32_t *p = pr.start; + while((uintptr_t)(p + 1) <= (uintptr_t)pr.start + pr.size) { + base = p; + uint32_t val = *p++; + if((val & 0xfe000000) == 0xfa000000) { + // BL + diff = ((val & 0xffffff) << 2); + goto ok; + } else if((val & 0x0f000000) == 0x0b000000) { + // BLX + diff = ((val & 0x1000000) >> 23) | ((val & 0xffffff) << 2) | 1; + goto ok; + } + } + } + return 0; + ok:; + addr_t baseaddr = ((char *) base) - ((char *) pr.start) + range->start + 4; + range->start = baseaddr + thumb; + if(diff & 0x800000) diff |= 0xff000000; + return baseaddr + diff; +} + +#define unparen(args...) args +#define find_anywhere_func(name, args1, args2) \ +addr_t b_find_##name##_anywhere(const struct binary *binary, unparen args1, int options) { \ + uint32_t end = binary->nsegments - 1; \ + for(uint32_t i = 0; i <= end; i++) { \ + range_t range = binary->segments[i].vm_range; \ + addr_t result = find_##name(range, unparen args2, i == end ? options : options & ~MUST_FIND); \ + if(result) return result; \ + } \ + return 0; /* won't reach */ \ +} + +find_anywhere_func(data, (const char *to_find, int align), (to_find, align)) +find_anywhere_func(string, (const char *string, int align), (string, align)) +find_anywhere_func(bytes, (const char *bytes, size_t len, int align), (bytes, len, align)) +find_anywhere_func(int32, (uint32_t number), (number)) + +struct pattern { + int16_t buf[128]; + ssize_t pattern_size, offset; + const char *name; + addr_t *result; +}; + +struct findmany { + range_t range; + int num_patterns; + struct pattern *patterns; +}; + +struct findmany *findmany_init(range_t range) { + struct findmany *fm = malloc(sizeof(*fm)); + fm->range = range; + fm->num_patterns = 0; + fm->patterns = NULL; + return fm; +} + +void findmany_add(addr_t *result, struct findmany *fm, const char *to_find) { + if(fm->num_patterns >= 32) { + die("too many patterns"); + } + fm->num_patterns++; + fm->patterns = realloc(fm->patterns, sizeof(struct pattern) * fm->num_patterns); + struct pattern *pat = &fm->patterns[fm->num_patterns - 1]; + + parse_pattern(to_find, pat->buf, &pat->pattern_size, &pat->offset); + pat->name = to_find; + pat->result = result; + *result = 0; +} + +struct node { + uint16_t next[16]; + uint32_t terminates; +}; + +struct node2 { + uint16_t next[16]; +}; + +struct findmany2 { + struct node *nodes; + uint8_t *index_paths; + uint16_t node_count; + struct node2 *nodes2; + uint16_t node2_count; +}; + +static inline int find_or_create(void **restrict array, void *restrict cmp, uint16_t *restrict num_items, int item_size, uint16_t *restrict node) { + char *p = *array; + for(int j = 0; j < *num_items; j++) { + if(!memcmp(p, cmp, item_size)) { + *node = j; + return false; + } + p += item_size; + } + if(*num_items == 65535) { + die("welp"); + } + *node = *num_items; + *array = realloc(*array, ++*num_items * item_size); + memcpy(*array + *node * item_size, cmp, item_size); + return true; +} + +static uint16_t findmany_recurse(const struct findmany *restrict fm, struct findmany2 *restrict fm2, uint8_t *restrict cur_index_path) { + // this part is inefficient + uint16_t node; + if(!find_or_create((void **) &fm2->index_paths, cur_index_path, &fm2->node_count, fm->num_patterns, &node)) { + // it found an existing node + return node; + } + /* + printf("findmany_recurse: created node %d with cur_index_path = ", node); + for(int p = 0; p < fm->num_patterns; p++) { + printf(" %d", (int) cur_index_path[p]); + } + printf("\n"); + */ + memcpy(fm2->index_paths + node * fm->num_patterns, cur_index_path, fm->num_patterns); + + fm2->nodes = realloc(fm2->nodes, fm2->node_count * sizeof(struct node)); + struct node *nodep = &fm2->nodes[node]; + + nodep->terminates = 0; + for(int p = 0; p < fm->num_patterns; p++) { + if(cur_index_path[p] == fm->patterns[p].pattern_size) { + nodep->terminates |= (1 << p); + cur_index_path[p] = 0; + } + } + + autofree uint8_t *new_index_path = malloc(fm->num_patterns); + for(uint8_t hi = 0; hi < 16; hi++) { + struct node2 n2; + for(uint8_t lo = 0; lo < 16; lo++) { + uint8_t chr = hi * 16 + lo; + + uint8_t orr = 0; // hack - a lot will point to 0 + + for(int p = 0; p < fm->num_patterns; p++) { + uint8_t idx = cur_index_path[p]; + int16_t comp = fm->patterns[p].buf[idx]; + if(comp == -1 || comp == chr) { + idx++; + } else { + idx = 0; + } + new_index_path[p] = idx; + orr |= idx; + } + + n2.next[lo] = orr ? findmany_recurse(fm, fm2, new_index_path) : 0; + } + nodep = &fm2->nodes[node]; + find_or_create((void **) &fm2->nodes2, &n2, &fm2->node2_count, sizeof(struct node2), &nodep->next[hi]); + } + + //printf("returning node %d\n", node); + return node; +} + +void findmany_go(struct findmany *fm) { + struct findmany2 fm2; + memset(&fm2, 0, sizeof(fm2)); + autofree uint8_t *cur_index_path = calloc(1, fm->num_patterns); +#ifdef PROFILING + clock_t a = clock(); +#endif + findmany_recurse(fm, &fm2, cur_index_path); +#ifdef PROFILING + clock_t b = clock(); + printf("it took %d clocks to prepare the DFA\n", (int) (b - a)); +#endif + + prange_t pr = rangeconv(fm->range, MUST_FIND); + uint8_t *start = pr.start; + struct node *cur = &fm2.nodes[0]; + for(uint8_t *ptr = start; ptr < start + pr.size; ptr++) { + uint8_t chr = *ptr; + + cur = &fm2.nodes[fm2.nodes2[cur->next[chr / 16]].next[chr % 16]]; + if(cur->terminates) { + for(int p = 0, bit = 1; p < fm->num_patterns; p++, bit <<= 1) { + if(cur->terminates & bit) { + struct pattern *pat = &fm->patterns[p]; + addr_t result = ptr - pat->pattern_size - start + fm->range.start + 1; + if(*pat->result) { + die("found [%s] multiple times in range: first at %08llx then at %08llx", pat->name, (uint64_t) *pat->result, (uint64_t) result); + } + *pat->result = result + pat->offset; + } + + } + } + } + + free(fm2.index_paths); // could be done earlier + free(fm2.nodes); + free(fm2.nodes2); + + for(int p = 0; p < fm->num_patterns; p++) { + struct pattern *pat = &fm->patterns[p]; + if(!*pat->result) { + die("didn't find [%s] in range(%llx, %zx)", pat->name, (uint64_t) fm->range.start, fm->range.size); + } + } + + free(fm->patterns); + free(fm); +} diff --git a/data/find.h b/data/find.h new file mode 100644 index 0000000..2eff006 --- /dev/null +++ b/data/find.h @@ -0,0 +1,31 @@ +#pragma once +#include "common.h" +struct binary; +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) < (b) ? (a) : (b)) + +__BEGIN_DECLS + +// Specify align as 0 if you only expect to find it at one place. +addr_t find_data(range_t range, const char *to_find, int align, int options); +addr_t find_string(range_t range, const char *string, int align, int options); +addr_t find_bytes(range_t range, const char *bytes, size_t len, int align, int options); +addr_t find_int32(range_t range, uint32_t number, int options); + +// helper functions +addr_t find_bof(range_t range, addr_t eof, int is_thumb); +uint32_t resolve_ldr(const struct binary *binary, addr_t addr); + +addr_t find_bl(range_t *range); + +#define b_find_anywhere b_find_data_anywhere +addr_t b_find_data_anywhere(const struct binary *binary, const char *to_find, int align, int options); +addr_t b_find_string_anywhere(const struct binary *binary, const char *string, int align, int options); +addr_t b_find_bytes_anywhere(const struct binary *binary, const char *bytes, size_t len, int align, int options); +addr_t b_find_int32_anywhere(const struct binary *binary, uint32_t number, int options); + +struct findmany *findmany_init(range_t range); +void findmany_add(addr_t *result, struct findmany *fm, const char *to_find); +void findmany_go(struct findmany *fm); + +__END_DECLS diff --git a/data/headers/machine.h b/data/headers/machine.h new file mode 100644 index 0000000..0518fae --- /dev/null +++ b/data/headers/machine.h @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2000-2007 Apple Computer, Inc. All rights reserved. + * + * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. The rights granted to you under the License + * may not be used to create, or enable the creation or redistribution of, + * unlawful or unlicensed copies of an Apple operating system, or to + * circumvent, violate, or enable the circumvention or violation of, any + * terms of an Apple operating system software license agreement. + * + * Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ + */ +/* + * Mach Operating System + * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University + * All Rights Reserved. + * + * Permission to use, copy, modify and distribute this software and its + * documentation is hereby granted, provided that both the copyright + * notice and this permission notice appear in all copies of the + * software, derivative works or modified versions, and any portions + * thereof, and that both notices appear in supporting documentation. + * + * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" + * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR + * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. + * + * Carnegie Mellon requests users of this software to return to + * + * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU + * School of Computer Science + * Carnegie Mellon University + * Pittsburgh PA 15213-3890 + * + * any improvements or extensions that they make and grant Carnegie Mellon + * the rights to redistribute these changes. + */ +/* File: machine.h + * Author: Avadis Tevanian, Jr. + * Date: 1986 + * + * Machine independent machine abstraction. + */ + +#ifndef _MACH_MACHINE_H_ +#define _MACH_MACHINE_H_ + +#include + +typedef int cpu_type_t; +typedef int cpu_subtype_t; +typedef int cpu_threadtype_t; + +#define CPU_STATE_MAX 4 + +#define CPU_STATE_USER 0 +#define CPU_STATE_SYSTEM 1 +#define CPU_STATE_IDLE 2 +#define CPU_STATE_NICE 3 + + + +/* + * Capability bits used in the definition of cpu_type. + */ +#define CPU_ARCH_MASK 0xff000000 /* mask for architecture bits */ +#define CPU_ARCH_ABI64 0x01000000 /* 64 bit ABI */ + +/* + * Machine types known by all. + */ + +#define CPU_TYPE_ANY ((cpu_type_t) -1) + +#define CPU_TYPE_VAX ((cpu_type_t) 1) +/* skip ((cpu_type_t) 2) */ +/* skip ((cpu_type_t) 3) */ +/* skip ((cpu_type_t) 4) */ +/* skip ((cpu_type_t) 5) */ +#define CPU_TYPE_MC680x0 ((cpu_type_t) 6) +#define CPU_TYPE_X86 ((cpu_type_t) 7) +#define CPU_TYPE_I386 CPU_TYPE_X86 /* compatibility */ +#define CPU_TYPE_X86_64 (CPU_TYPE_X86 | CPU_ARCH_ABI64) + +/* skip CPU_TYPE_MIPS ((cpu_type_t) 8) */ +/* skip ((cpu_type_t) 9) */ +#define CPU_TYPE_MC98000 ((cpu_type_t) 10) +#define CPU_TYPE_HPPA ((cpu_type_t) 11) +#define CPU_TYPE_ARM ((cpu_type_t) 12) +#define CPU_TYPE_MC88000 ((cpu_type_t) 13) +#define CPU_TYPE_SPARC ((cpu_type_t) 14) +#define CPU_TYPE_I860 ((cpu_type_t) 15) +/* skip CPU_TYPE_ALPHA ((cpu_type_t) 16) */ +/* skip ((cpu_type_t) 17) */ +#define CPU_TYPE_POWERPC ((cpu_type_t) 18) +#define CPU_TYPE_POWERPC64 (CPU_TYPE_POWERPC | CPU_ARCH_ABI64) + +/* + * Machine subtypes (these are defined here, instead of in a machine + * dependent directory, so that any program can get all definitions + * regardless of where is it compiled). + */ + +/* + * Capability bits used in the definition of cpu_subtype. + */ +#define CPU_SUBTYPE_MASK 0xff000000 /* mask for feature flags */ +#define CPU_SUBTYPE_LIB64 0x80000000 /* 64 bit libraries */ + + +/* + * Object files that are hand-crafted to run on any + * implementation of an architecture are tagged with + * CPU_SUBTYPE_MULTIPLE. This functions essentially the same as + * the "ALL" subtype of an architecture except that it allows us + * to easily find object files that may need to be modified + * whenever a new implementation of an architecture comes out. + * + * It is the responsibility of the implementor to make sure the + * software handles unsupported implementations elegantly. + */ +#define CPU_SUBTYPE_MULTIPLE ((cpu_subtype_t) -1) +#define CPU_SUBTYPE_LITTLE_ENDIAN ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_BIG_ENDIAN ((cpu_subtype_t) 1) + +/* + * Machine threadtypes. + * This is none - not defined - for most machine types/subtypes. + */ +#define CPU_THREADTYPE_NONE ((cpu_threadtype_t) 0) + +/* + * VAX subtypes (these do *not* necessary conform to the actual cpu + * ID assigned by DEC available via the SID register). + */ + +#define CPU_SUBTYPE_VAX_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_VAX780 ((cpu_subtype_t) 1) +#define CPU_SUBTYPE_VAX785 ((cpu_subtype_t) 2) +#define CPU_SUBTYPE_VAX750 ((cpu_subtype_t) 3) +#define CPU_SUBTYPE_VAX730 ((cpu_subtype_t) 4) +#define CPU_SUBTYPE_UVAXI ((cpu_subtype_t) 5) +#define CPU_SUBTYPE_UVAXII ((cpu_subtype_t) 6) +#define CPU_SUBTYPE_VAX8200 ((cpu_subtype_t) 7) +#define CPU_SUBTYPE_VAX8500 ((cpu_subtype_t) 8) +#define CPU_SUBTYPE_VAX8600 ((cpu_subtype_t) 9) +#define CPU_SUBTYPE_VAX8650 ((cpu_subtype_t) 10) +#define CPU_SUBTYPE_VAX8800 ((cpu_subtype_t) 11) +#define CPU_SUBTYPE_UVAXIII ((cpu_subtype_t) 12) + +/* + * 680x0 subtypes + * + * The subtype definitions here are unusual for historical reasons. + * NeXT used to consider 68030 code as generic 68000 code. For + * backwards compatability: + * + * CPU_SUBTYPE_MC68030 symbol has been preserved for source code + * compatability. + * + * CPU_SUBTYPE_MC680x0_ALL has been defined to be the same + * subtype as CPU_SUBTYPE_MC68030 for binary comatability. + * + * CPU_SUBTYPE_MC68030_ONLY has been added to allow new object + * files to be tagged as containing 68030-specific instructions. + */ + +#define CPU_SUBTYPE_MC680x0_ALL ((cpu_subtype_t) 1) +#define CPU_SUBTYPE_MC68030 ((cpu_subtype_t) 1) /* compat */ +#define CPU_SUBTYPE_MC68040 ((cpu_subtype_t) 2) +#define CPU_SUBTYPE_MC68030_ONLY ((cpu_subtype_t) 3) + +/* + * I386 subtypes + */ + +#define CPU_SUBTYPE_INTEL(f, m) ((cpu_subtype_t) (f) + ((m) << 4)) + +#define CPU_SUBTYPE_I386_ALL CPU_SUBTYPE_INTEL(3, 0) +#define CPU_SUBTYPE_386 CPU_SUBTYPE_INTEL(3, 0) +#define CPU_SUBTYPE_486 CPU_SUBTYPE_INTEL(4, 0) +#define CPU_SUBTYPE_486SX CPU_SUBTYPE_INTEL(4, 8) // 8 << 4 = 128 +#define CPU_SUBTYPE_586 CPU_SUBTYPE_INTEL(5, 0) +#define CPU_SUBTYPE_PENT CPU_SUBTYPE_INTEL(5, 0) +#define CPU_SUBTYPE_PENTPRO CPU_SUBTYPE_INTEL(6, 1) +#define CPU_SUBTYPE_PENTII_M3 CPU_SUBTYPE_INTEL(6, 3) +#define CPU_SUBTYPE_PENTII_M5 CPU_SUBTYPE_INTEL(6, 5) +#define CPU_SUBTYPE_CELERON CPU_SUBTYPE_INTEL(7, 6) +#define CPU_SUBTYPE_CELERON_MOBILE CPU_SUBTYPE_INTEL(7, 7) +#define CPU_SUBTYPE_PENTIUM_3 CPU_SUBTYPE_INTEL(8, 0) +#define CPU_SUBTYPE_PENTIUM_3_M CPU_SUBTYPE_INTEL(8, 1) +#define CPU_SUBTYPE_PENTIUM_3_XEON CPU_SUBTYPE_INTEL(8, 2) +#define CPU_SUBTYPE_PENTIUM_M CPU_SUBTYPE_INTEL(9, 0) +#define CPU_SUBTYPE_PENTIUM_4 CPU_SUBTYPE_INTEL(10, 0) +#define CPU_SUBTYPE_PENTIUM_4_M CPU_SUBTYPE_INTEL(10, 1) +#define CPU_SUBTYPE_ITANIUM CPU_SUBTYPE_INTEL(11, 0) +#define CPU_SUBTYPE_ITANIUM_2 CPU_SUBTYPE_INTEL(11, 1) +#define CPU_SUBTYPE_XEON CPU_SUBTYPE_INTEL(12, 0) +#define CPU_SUBTYPE_XEON_MP CPU_SUBTYPE_INTEL(12, 1) + +#define CPU_SUBTYPE_INTEL_FAMILY(x) ((x) & 15) +#define CPU_SUBTYPE_INTEL_FAMILY_MAX 15 + +#define CPU_SUBTYPE_INTEL_MODEL(x) ((x) >> 4) +#define CPU_SUBTYPE_INTEL_MODEL_ALL 0 + +/* + * X86 subtypes. + */ + +#define CPU_SUBTYPE_X86_ALL ((cpu_subtype_t)3) +#define CPU_SUBTYPE_X86_64_ALL ((cpu_subtype_t)3) +#define CPU_SUBTYPE_X86_ARCH1 ((cpu_subtype_t)4) + + +#define CPU_THREADTYPE_INTEL_HTT ((cpu_threadtype_t) 1) + +/* + * Mips subtypes. + */ + +#define CPU_SUBTYPE_MIPS_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_MIPS_R2300 ((cpu_subtype_t) 1) +#define CPU_SUBTYPE_MIPS_R2600 ((cpu_subtype_t) 2) +#define CPU_SUBTYPE_MIPS_R2800 ((cpu_subtype_t) 3) +#define CPU_SUBTYPE_MIPS_R2000a ((cpu_subtype_t) 4) /* pmax */ +#define CPU_SUBTYPE_MIPS_R2000 ((cpu_subtype_t) 5) +#define CPU_SUBTYPE_MIPS_R3000a ((cpu_subtype_t) 6) /* 3max */ +#define CPU_SUBTYPE_MIPS_R3000 ((cpu_subtype_t) 7) + +/* + * MC98000 (PowerPC) subtypes + */ +#define CPU_SUBTYPE_MC98000_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_MC98601 ((cpu_subtype_t) 1) + +/* + * HPPA subtypes for Hewlett-Packard HP-PA family of + * risc processors. Port by NeXT to 700 series. + */ + +#define CPU_SUBTYPE_HPPA_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_HPPA_7100 ((cpu_subtype_t) 0) /* compat */ +#define CPU_SUBTYPE_HPPA_7100LC ((cpu_subtype_t) 1) + +/* + * MC88000 subtypes. + */ +#define CPU_SUBTYPE_MC88000_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_MC88100 ((cpu_subtype_t) 1) +#define CPU_SUBTYPE_MC88110 ((cpu_subtype_t) 2) + +/* + * SPARC subtypes + */ +#define CPU_SUBTYPE_SPARC_ALL ((cpu_subtype_t) 0) + +/* + * I860 subtypes + */ +#define CPU_SUBTYPE_I860_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_I860_860 ((cpu_subtype_t) 1) + +/* + * PowerPC subtypes + */ +#define CPU_SUBTYPE_POWERPC_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_POWERPC_601 ((cpu_subtype_t) 1) +#define CPU_SUBTYPE_POWERPC_602 ((cpu_subtype_t) 2) +#define CPU_SUBTYPE_POWERPC_603 ((cpu_subtype_t) 3) +#define CPU_SUBTYPE_POWERPC_603e ((cpu_subtype_t) 4) +#define CPU_SUBTYPE_POWERPC_603ev ((cpu_subtype_t) 5) +#define CPU_SUBTYPE_POWERPC_604 ((cpu_subtype_t) 6) +#define CPU_SUBTYPE_POWERPC_604e ((cpu_subtype_t) 7) +#define CPU_SUBTYPE_POWERPC_620 ((cpu_subtype_t) 8) +#define CPU_SUBTYPE_POWERPC_750 ((cpu_subtype_t) 9) +#define CPU_SUBTYPE_POWERPC_7400 ((cpu_subtype_t) 10) +#define CPU_SUBTYPE_POWERPC_7450 ((cpu_subtype_t) 11) +#define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100) + +/* + * ARM subtypes + */ +#define CPU_SUBTYPE_ARM_ALL ((cpu_subtype_t) 0) +#define CPU_SUBTYPE_ARM_V4T ((cpu_subtype_t) 5) +#define CPU_SUBTYPE_ARM_V6 ((cpu_subtype_t) 6) +#define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7) +#define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8) +#define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9) + +/* + * CPU families (sysctl hw.cpufamily) + * + * These are meant to identify the CPU's marketing name - an + * application can map these to (possibly) localized strings. + * NB: the encodings of the CPU families are intentionally arbitrary. + * There is no ordering, and you should never try to deduce whether + * or not some feature is available based on the family. + * Use feature flags (eg, hw.optional.altivec) to test for optional + * functionality. + */ +#define CPUFAMILY_UNKNOWN 0 +#define CPUFAMILY_POWERPC_G3 0xcee41549 +#define CPUFAMILY_POWERPC_G4 0x77c184ae +#define CPUFAMILY_POWERPC_G5 0xed76d8aa +#define CPUFAMILY_INTEL_6_13 0xaa33392b +#define CPUFAMILY_INTEL_YONAH 0x73d67300 +#define CPUFAMILY_INTEL_MEROM 0x426f69ef +#define CPUFAMILY_INTEL_PENRYN 0x78ea4fbc +#define CPUFAMILY_INTEL_NEHALEM 0x6b5a4cd2 +#define CPUFAMILY_INTEL_WESTMERE 0x573b5eec +#define CPUFAMILY_INTEL_SANDYBRIDGE 0x5490b78c +#define CPUFAMILY_ARM_9 0xe73283ae +#define CPUFAMILY_ARM_11 0x8ff620d8 +#define CPUFAMILY_ARM_XSCALE 0x53b005f5 +#define CPUFAMILY_ARM_13 0x0cc90e64 +#define CPUFAMILY_ARM_14 0x96077ef1 + +/* The following synonyms are deprecated: */ +#define CPUFAMILY_INTEL_6_14 CPUFAMILY_INTEL_YONAH +#define CPUFAMILY_INTEL_6_15 CPUFAMILY_INTEL_MEROM +#define CPUFAMILY_INTEL_6_23 CPUFAMILY_INTEL_PENRYN +#define CPUFAMILY_INTEL_6_26 CPUFAMILY_INTEL_NEHALEM + +#define CPUFAMILY_INTEL_CORE CPUFAMILY_INTEL_YONAH +#define CPUFAMILY_INTEL_CORE2 CPUFAMILY_INTEL_MEROM + + +#endif /* _MACH_MACHINE_H_ */ diff --git a/data/ios-classify.h b/data/ios-classify.h new file mode 100644 index 0000000..d7a2aeb --- /dev/null +++ b/data/ios-classify.h @@ -0,0 +1,24 @@ +// the spec macro chooses between alternatives depending on the "class" +// possible "classes": armv6 pre 4.3, armv7 pre 4.3, 4.3.x, 5.0.x + +static unsigned int _armv6 = 0; +static unsigned int _armv7 = 1; +static unsigned int _43 = 2; +static unsigned int _50 = 3; + +#define spec_(c1, v1, c2, v2, c3, v3, c4, v4, ...) \ + (class >= (c1) ? (v1) : \ + class >= (c2) ? (v2) : \ + class >= (c3) ? (v3) : \ + class >= (c4) ? (v4) : \ + (die("no valid alternative"), (typeof(v1+0)) 0)) +#define spec(args...) spec_(args, 10, 0, 10, 0, 10, 0) + +#define is_armv7(binary) (binary->cpusubtype == 9) + +static unsigned int classify(const struct binary *binary) { + if(!is_armv7(binary)) return _armv6; + else if(b_sym(binary, "_mach_gss_hold_cred", 0)) return _50; + else if(b_sym(binary, "_vfs_getattr", 0)) return _43; + else return _armv7; +} diff --git a/data/ldid_wrapper b/data/ldid_wrapper new file mode 100755 index 0000000..32c9eb0 --- /dev/null +++ b/data/ldid_wrapper @@ -0,0 +1,22 @@ +#!/bin/sh +set -e +ldid=ldid +for last; do + ldid="$ldid $old" + old="$last" +done +archs="$(lipo -info "$last")" +if [ -z "$(echo $archs | grep are:)" ]; then + $ldid "$last" +else + archs="$(echo $archs | sed 's/^.*are: //')" + temp=$(mktemp -d /tmp/ldid_wrapper.XXXXX) + for arch in $archs; do + lipo -thin $arch -output $temp/$arch "$last" + $ldid $temp/$arch + done + lipo -create -output "$last" $temp/* + rm -rf $temp +fi + + diff --git a/data/lzss.c b/data/lzss.c new file mode 100644 index 0000000..8fe9d47 --- /dev/null +++ b/data/lzss.c @@ -0,0 +1,99 @@ +#ifdef IMG3_SUPPORT +#include +#include +#include + +#define BASE 65521L /* largest prime smaller than 65536 */ +#define NMAX 5000 +// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 + +#define DO1(buf,i) {s1 += buf[i]; s2 += s1;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +uint32_t lzadler32(uint8_t *buf, int32_t len) +{ + unsigned long s1 = 1; // adler & 0xffff; + unsigned long s2 = 0; // (adler >> 16) & 0xffff; + int k; + + while (len > 0) { + k = len < NMAX ? len : NMAX; + len -= k; + while (k >= 16) { + DO16(buf); + buf += 16; + k -= 16; + } + if (k != 0) do { + s1 += *buf++; + s2 += s1; + } while (--k); + s1 %= BASE; + s2 %= BASE; + } + return (s2 << 16) | s1; +} + + + +/************************************************************** + LZSS.C -- A Data Compression Program +*************************************************************** + 4/6/1989 Haruhiko Okumura + Use, distribute, and modify this program freely. + Please send me your improved versions. + PC-VAN SCIENCE + NIFTY-Serve PAF01022 + CompuServe 74050,1022 + +**************************************************************/ + +#define N 4096 /* size of ring buffer - must be power of 2 */ +#define F 18 /* upper limit for match_length */ +#define THRESHOLD 2 /* encode string into position and length + if match_length is greater than this */ +int +decompress_lzss(uint8_t *dst, uint8_t *src, uint32_t srclen) +{ + /* ring buffer of size N, with extra F-1 bytes to aid string comparison */ + uint8_t text_buf[N + F - 1]; + uint8_t *dststart = dst; + uint8_t *srcend = src + srclen; + int i, j, k, r, c; + unsigned int flags; + + dst = dststart; + srcend = src + srclen; + memset(text_buf, ' ', N - F); + r = N - F; + flags = 0; + for ( ; ; ) { + if (((flags >>= 1) & 0x100) == 0) { + if (src < srcend) c = *src++; else break; + flags = c | 0xFF00; /* uses higher byte cleverly */ + } /* to count eight */ + if (flags & 1) { + if (src < srcend) c = *src++; else break; + *dst++ = c; + text_buf[r++] = c; + r &= (N - 1); + } else { + if (src < srcend) i = *src++; else break; + if (src < srcend) j = *src++; else break; + i |= ((j & 0xF0) << 4); + j = (j & 0x0F) + THRESHOLD; + for (k = 0; k <= j; k++) { + c = text_buf[(i + k) & (N - 1)]; + *dst++ = c; + text_buf[r++] = c; + r &= (N - 1); + } + } + } + + return dst - dststart; +} +#endif diff --git a/data/lzss.h b/data/lzss.h new file mode 100644 index 0000000..b642103 --- /dev/null +++ b/data/lzss.h @@ -0,0 +1,3 @@ +#include +uint32_t lzadler32(uint8_t *buf, int32_t len); +int decompress_lzss(uint8_t *dst, uint8_t *src, uint32_t srclen); diff --git a/data/mach-o/binary.c b/data/mach-o/binary.c new file mode 100644 index 0000000..25aaef2 --- /dev/null +++ b/data/mach-o/binary.c @@ -0,0 +1,474 @@ +#include "binary.h" +#include "headers/loader.h" +#include "headers/nlist.h" +#include "headers/fat.h" +#include "read_dyld_info.h" + +const int desired_cputype = CPU_TYPE_ARM; +const int desired_cpusubtype = CPU_SUBTYPE_ARM_V7; + +static addr_t sym(const struct binary *binary, const char *name, int options); +static void copy_syms(const struct binary *binary, struct data_sym **syms, uint32_t *nsyms, int options); + +static void do_load_commands(struct binary *binary) { + struct mach_header *hdr = b_mach_hdr(binary); + if(!prange_check(binary, (prange_t) {hdr, hdr->sizeofcmds})) { + die("not enough room for commands"); + } + uint32_t nsegs = 0; + CMD_ITERATE(hdr, cmd) { + if(cmd + 1 > end || cmd > end - 1) { + die("sizeofcmds is not even"); + } + if(cmd->cmdsize < sizeof(struct load_command)) { + die("tiny command"); + } + if(cmd->cmdsize > (size_t) ((char *) end - (char *) cmd)) { + die("cmdsize overflows (%u)", cmd->cmdsize); + } + uint32_t required = 0; + switch(cmd->cmd) { + MACHO_SPECIALIZE( + case LC_SEGMENT_X: + required = sizeof(segment_command_x); + nsegs++; + break; + ) + case LC_REEXPORT_DYLIB: + required = sizeof(struct dylib_command); + break; + case LC_SYMTAB: + required = sizeof(struct symtab_command); + break; + case LC_DYSYMTAB: + required = sizeof(struct dysymtab_command); + break; + case LC_DYLD_INFO: + case LC_DYLD_INFO_ONLY: + required = sizeof(struct dyld_info_command); + break; + case LC_ID_DYLIB: + required = sizeof(struct dylib_command); + break; + } + + if(cmd->cmdsize < required) { + die("cmdsize (%u) too small for cmd (0x%x)", cmd->cmdsize, cmd->cmd); + } + } + if(nsegs > MAX_ARRAY(struct data_segment)) { + die("segment overflow"); + } + binary->nsegments = nsegs; + struct data_segment *seg = binary->segments = malloc(sizeof(*binary->segments) * binary->nsegments); + CMD_ITERATE(hdr, cmd) { + switch(cmd->cmd) { + MACHO_SPECIALIZE( + case LC_SEGMENT_X: { + segment_command_x *scmd = (void *) cmd; + if((scmd->cmdsize - sizeof(*scmd)) / sizeof(section_x) < scmd->nsects) { + die("section overflow"); + } + seg->file_range = (range_t) {binary, scmd->fileoff, scmd->filesize}; + seg->vm_range = (range_t) {binary, scmd->vmaddr, scmd->vmsize}; + seg->native_segment = cmd; + seg++; + break; + } + ) + } + } +} + +static void do_symbols(struct binary *binary) { + binary->mach = calloc(sizeof(*binary->mach), 1); + binary->mach->hdr = b_mach_hdr(binary); + + CMD_ITERATE(b_mach_hdr(binary), cmd) { + MACHO_SPECIALIZE( + if(cmd->cmd == LC_SEGMENT_X) { + segment_command_x *seg = (void *) cmd; + if(seg->fileoff == 0) { + binary->mach->export_baseaddr = seg->vmaddr; + } + } + ) + if(cmd->cmd == LC_SYMTAB) { + struct symtab_command *scmd = (void *) cmd; + if(scmd->nsyms > MAX_ARRAY(struct data_sym) || scmd->nsyms > MAX_ARRAY(struct nlist_64)) { + die("ridiculous number of symbols (%u)", scmd->nsyms); + } + binary->mach->nsyms = scmd->nsyms; + binary->mach->strsize = scmd->strsize; + binary->mach->symtab = rangeconv_off((range_t) {binary, scmd->symoff, scmd->nsyms * (b_pointer_size(binary) == 8 ? sizeof(struct nlist_64) : sizeof(struct nlist))}, MUST_FIND).start; + binary->mach->strtab = rangeconv_off((range_t) {binary, scmd->stroff, scmd->strsize}, MUST_FIND).start; + if(binary->mach->strtab[binary->mach->strsize - 1]) { + die("string table does not end with \\0"); + } + } else if(cmd->cmd == LC_DYSYMTAB) { + binary->mach->dysymtab = (void *) cmd; + } else if(cmd->cmd == LC_DYLD_INFO_ONLY || cmd->cmd == LC_DYLD_INFO) { + struct dyld_info_command *dcmd = (void *) cmd; + binary->mach->dyld_info = dcmd; + binary->mach->export_trie = rangeconv_off((range_t) {binary, dcmd->export_off, dcmd->export_size}, MUST_FIND); + } + } + const struct dysymtab_command *dc; + if(binary->mach->symtab && (dc = binary->mach->dysymtab)) { + size_t size; + MACHO_SPECIALIZE_POINTER_SIZE(binary, size = sizeof(nlist_x);) +#define do_it(isym, nsym, x_symtab, x_nsyms) \ + if(dc->isym <= binary->mach->nsyms && dc->nsym <= binary->mach->nsyms - dc->isym && dc->nsym <= MAX_ARRAY(struct nlist_64) && dc->nsym <= MAX_ARRAY(struct data_sym)) { \ + binary->mach->x_symtab = binary->mach->symtab + dc->isym * size; \ + binary->mach->x_nsyms = dc->nsym; \ + } else { \ + fprintf(stderr, "warning: bad %s/%s (%u, %u)\n", #isym, #nsym, dc->isym, dc->nsym); \ + } + do_it(iextdefsym, nextdefsym, ext_symtab, ext_nsyms) + do_it(iundefsym, nundefsym, imp_symtab, imp_nsyms) +#undef do_it + } else { + binary->mach->ext_symtab = binary->mach->symtab; + binary->mach->ext_nsyms = binary->mach->nsyms; + } +} + +void b_prange_load_macho(struct binary *binary, prange_t pr, size_t offset, const char *name) { + b_prange_load_macho_nosyms(binary, pr, offset, name); + do_symbols(binary); + binary->_sym = sym; + binary->_copy_syms = copy_syms; +} + +void b_prange_load_macho_nosyms(struct binary *binary, prange_t pr, size_t offset, const char *name) { +#define _arg name + binary->valid = true; + + binary->header_offset = offset; + + if(offset >= pr.size || offset - pr.size < sizeof(struct mach_header)) { + die("not enough room"); + } + + struct mach_header *hdr = pr.start + offset; + if(hdr->magic == MH_MAGIC) { + // thin file + binary->valid_range = pr; + binary->pointer_size = 4; + } else if(ADDR64 && hdr->magic == MH_MAGIC_64) { + binary->valid_range = pr; + binary->pointer_size = 8; + } else if(hdr->magic == FAT_CIGAM) { + if(offset) die("fat, offset != 0"); + + struct fat_header *fathdr = (void *) hdr; + struct fat_arch *arch = (void *)(fathdr + 1); + uint32_t nfat_arch = SWAP32(fathdr->nfat_arch); + if(nfat_arch > (pr.size - sizeof(struct fat_header)) / sizeof(struct fat_arch)) { + die("fat header is too small"); + } + if(!nfat_arch) { + die("fat file is empty"); + } + + prange_t fat_pr = {NULL, 0}; /* no, gcc, it won't be used uninitialized */ + int highest_score = 0; + while(nfat_arch--) { + int score = 0; + if(desired_cputype != CPU_TYPE_ANY && SWAP32(arch->cputype) == desired_cputype) { + score = 1; + if(arch->cpusubtype == 0 || (desired_cpusubtype != 0 && SWAP32(arch->cpusubtype) == desired_cpusubtype)) { + score = 2; + } + } + if(score >= highest_score) { + highest_score = score; + + uint32_t fat_offset = SWAP32(arch->offset); + if(fat_offset >= pr.size || pr.size - fat_offset < sizeof(struct mach_header)) { + die("fat_offset too big"); + } + fat_pr = (prange_t) {pr.start + fat_offset, pr.size - fat_offset}; + } + arch++; + } + + binary->valid_range = fat_pr; + } else if(hdr->magic == MH_CIGAM || hdr->magic == MH_CIGAM_64 || hdr->magic == FAT_MAGIC) { + die("wrong endian"); + } else { + die("(%08x) what is this I don't even", hdr->magic); + } + + binary->cputype = b_mach_hdr(binary)->cputype; + binary->cpusubtype = b_mach_hdr(binary)->cpusubtype; + + do_load_commands(binary); +#undef _arg +} + +static inline struct data_sym convert_nlist(const struct binary *binary, const void *nl_, int options) { + struct data_sym result; + MACHO_SPECIALIZE_POINTER_SIZE(binary, + const nlist_x *nl = nl_; + uint32_t strx = nl->n_un.n_strx; + if(strx >= binary->mach->strsize) { + die("insane strx: %u", strx); + } + result.name = binary->mach->strtab + strx; + result.address = nl->n_value; + if((options & TO_EXECUTE) && (nl->n_desc & N_ARM_THUMB_DEF)) { + result.address |= 1; + } + ) + return result; +} + +void *b_macho_nth_symbol(const struct binary *binary, uint32_t n) { + if(!binary->mach->symtab) { + die("no symbol table"); + } + if(n >= binary->mach->nsyms) { + die("sym too high: %u", n); + } + MACHO_SPECIALIZE_POINTER_SIZE(binary, + nlist_x *nl = binary->mach->symtab + n * sizeof(*nl); + if((uint32_t) nl->n_un.n_strx >= binary->mach->strsize) { + die("insane strx: %d", (int) nl->n_un.n_strx); + } + return nl; + ) +} + + +static addr_t sym_nlist(const struct binary *binary, const char *name, int options) { + // I stole dyld's codez + const struct nlist *base = binary->mach->ext_symtab; + for(uint32_t n = binary->mach->ext_nsyms; n > 0; n /= 2) { + const struct nlist *pivot = base + n/2; + struct data_sym ds = convert_nlist(binary, pivot, options); + int cmp = strcmp(name, ds.name); + if(cmp == 0) { + return ds.address; + } else if(cmp > 0) { + base = pivot + 1; + n--; + } + } + + for(unsigned int i = 0; i < binary->nreexports; i++) { + addr_t result; + if(result = b_sym(&binary->reexports[i], name, options)) { + return result; + } + } + + return 0; +} + +static addr_t trie_recurse(const struct binary *binary, void *ptr, char *start, char *end, const char *name0, const char *name, int options) { + if(start == end) return 0; + uint8_t terminal_size = read_int(&ptr, end, uint8_t); + if(terminal_size) { + uint32_t flags = read_uleb128(&ptr, end); + uint32_t address = read_uleb128(&ptr, end); + uint32_t resolver = 0; + if(flags & 0x10) { + resolver = read_uleb128(&ptr, end); + } + if(!name[0]) { + if(resolver) { + fprintf(stderr, "trie_recurse: %s has a resolver; returning failure\n", name0); + return 0; + } + if(flags & 8) { + // indirect definition + address--; + if(address >= binary->nreexports) { + die("invalid sub-library %d", address); + } + return b_sym(&binary->reexports[address], name0, options); + } + if(binary->cputype == CPU_TYPE_ARM && !(options & TO_EXECUTE)) { + address &= ~1u; + } + return ((addr_t) address) + binary->mach->export_baseaddr; + } + } + + uint8_t child_count = read_int(&ptr, end, uint8_t); + while(child_count--) { + const char *name2 = name; + char c; + while(1) { + c = read_int(&ptr, end, char); + if(!c) { + uint64_t offset = read_uleb128(&ptr, end); + if(offset >= (size_t) (end - start)) die("invalid child offset"); + return trie_recurse(binary, start + offset, start, end, name0, name2, options); + } + if(c != *name2++) { + break; + } + } + // skip the rest + read_cstring(&ptr, end); + read_uleb128(&ptr, end); + } + return 0; +} + +static addr_t sym_trie(const struct binary *binary, const char *name, int options) { + return trie_recurse(binary, + binary->mach->export_trie.start, + binary->mach->export_trie.start, + (char *)binary->mach->export_trie.start + binary->mach->export_trie.size, + name, + name, + options); +} + +static addr_t sym_private(const struct binary *binary, const char *name, int options) { + if(!binary->mach->symtab) { + die("we wanted %s but there is no symbol table", name); + } + MACHO_SPECIALIZE_POINTER_SIZE(binary, + const nlist_x *base = binary->mach->symtab; + for(uint32_t i = 0; i < binary->mach->nsyms; i++) { + struct data_sym ds = convert_nlist(binary, base + i, options); + if(!strcmp(ds.name, name)) return ds.address; + } + ) + return 0; +} + + +static addr_t sym_imported(const struct binary *binary, const char *name, __unused int options) { + // most of this function is copied and pasted from link.c :$ + CMD_ITERATE(b_mach_hdr(binary), cmd) { + MACHO_SPECIALIZE( + if(cmd->cmd == LC_SEGMENT_X) { + segment_command_x *seg = (void *) cmd; + section_x *sect = (void *) (seg + 1); + for(uint32_t i = 0; i < seg->nsects; i++, sect++) { + uint8_t type = sect->flags & SECTION_TYPE; + if(type != S_NON_LAZY_SYMBOL_POINTERS && type != S_LAZY_SYMBOL_POINTERS) continue; + + uint32_t indirect_table_offset = sect->reserved1; + uint32_t *indirect = rangeconv_off((range_t) {binary, (addr_t) (binary->mach->dysymtab->indirectsymoff + indirect_table_offset*sizeof(uint32_t)), (sect->size / 4) * sizeof(uint32_t)}, MUST_FIND).start; + + for(uint32_t i = 0; i < sect->size / 4; i++) { + uint32_t sym = indirect[i]; + if(sym == INDIRECT_SYMBOL_LOCAL || sym == INDIRECT_SYMBOL_ABS) continue; + nlist_x *nl = b_macho_nth_symbol(binary, sym); + if(!strcmp(binary->mach->strtab + nl->n_un.n_strx, name)) { + return sect->addr + 4*i; + } + } + } + } + ) + } + return 0; +} + +static addr_t sym(const struct binary *binary, const char *name, int options) { + addr_t (*func)(const struct binary *binary, const char *name, int options); + if(options & PRIVATE_SYM) + func = sym_private; + else if(options & IMPORTED_SYM) + func = sym_imported; + else if(binary->mach->export_trie.start) + func = sym_trie; + else + func = sym_nlist; + return func(binary, name, options & ~MUST_FIND); +} + +static void copy_syms(const struct binary *binary, struct data_sym **syms, uint32_t *nsyms, int options) { + uint32_t n; + const void *nl; + size_t size; + MACHO_SPECIALIZE_POINTER_SIZE(binary, size = sizeof(nlist_x);) + bool can_be_zero = false; + if(options & PRIVATE_SYM) { + nl = binary->mach->symtab; + n = binary->mach->nsyms; + } else if(options & IMPORTED_SYM) { + nl = binary->mach->imp_symtab; + n = binary->mach->imp_nsyms; + can_be_zero = true; + } else { + nl = binary->mach->ext_symtab; + n = binary->mach->ext_nsyms; + } + struct data_sym *s = *syms = malloc(sizeof(struct data_sym) * n); + for(uint32_t i = 0; i < n; i++) { + *s = convert_nlist(binary, nl, options); + nl += size; + if(can_be_zero || s->address) s++; + } + *nsyms = s - *syms; +} + +range_t b_macho_segrange(const struct binary *binary, const char *segname) { + CMD_ITERATE(b_mach_hdr(binary), cmd) { + MACHO_SPECIALIZE( + if(cmd->cmd == LC_SEGMENT_X) { + segment_command_x *seg = (void *) cmd; + if(!strncmp(seg->segname, segname, 16)) { + return (range_t) {binary, seg->vmaddr, seg->filesize}; + } + } + ) + } + die("no such segment %s", segname); +} + +range_t b_macho_sectrange(const struct binary *binary, const char *segname, const char *sectname) { + CMD_ITERATE(b_mach_hdr(binary), cmd) { + MACHO_SPECIALIZE( + if(cmd->cmd == LC_SEGMENT_X) { + segment_command_x *seg = (void *) cmd; + if(!strncmp(seg->segname, segname, 16)) { + section_x *sect = (void *) (seg + 1); + for(uint32_t i = 0; i < seg->nsects; i++) { + if(!strncmp(sect[i].sectname, sectname, 16)) { + return (range_t) {binary, sect->addr, sect->size}; + } + } + } + } + ) + } + die("no such segment %s", segname); +} + +void b_load_macho(struct binary *binary, const char *filename) { + return b_prange_load_macho(binary, load_file(filename, true, NULL), 0, filename); +} + +addr_t b_macho_reloc_base(const struct binary *binary) { + // copying dyld's behavior + CMD_ITERATE(b_mach_hdr(binary), cmd) { + MACHO_SPECIALIZE( + if(cmd->cmd == LC_SEGMENT_X) { + segment_command_x *seg = (void *) cmd; + if(b_mach_hdr(binary)->cputype != CPU_TYPE_X86_64 || (seg->initprot & PROT_WRITE)) { + return seg->vmaddr; + } + } + ) + } + die("no segments"); +} + +const char *convert_lc_str(const struct load_command *cmd, uint32_t offset) { + const char *ret = ((const char *) cmd) + offset; + size_t size = cmd->cmdsize - offset; + if(offset >= cmd->cmdsize || strnlen(ret, size) == size) { + die("bad lc_str"); + } + return ret; +} + diff --git a/data/mach-o/binary.h b/data/mach-o/binary.h new file mode 100644 index 0000000..ecddd55 --- /dev/null +++ b/data/mach-o/binary.h @@ -0,0 +1,76 @@ +#pragma once +#include "../binary.h" +#include "headers/loader.h" + +#define CMD_ITERATE(hdr, cmd) \ + for(struct load_command *cmd = \ + (struct load_command *) ((uint32_t *) ((hdr) + 1) + (ADDR64 ? ((hdr)->magic & 1) : 0)), \ + *end = (struct load_command *) ((char *) cmd + (hdr)->sizeofcmds); \ + cmd < end; \ + cmd = (struct load_command *) ((char *) cmd + cmd->cmdsize)) + +#define LC_SEGMENT_X sizeof(_spec_LC_SEGMENT_X) +#define pointer_size_x sizeof(_spec_pointer_size_x) + +#define _MACHO_SPECIALIZE(_LC_SEGMENT_X, _segment_command_x, _section_x, _nlist_x, _pointer_size_x, text...) { \ + typedef struct _segment_command_x segment_command_x; \ + typedef struct _section_x section_x; \ + typedef struct _nlist_x nlist_x; \ + typedef char _spec_LC_SEGMENT_X[_LC_SEGMENT_X]; \ + typedef char _spec_pointer_size_x[_pointer_size_x]; \ + text \ +} +#define _MACHO_SPECIALIZE_64(text...) _MACHO_SPECIALIZE(LC_SEGMENT_64, segment_command_64, section_64, nlist_64, 8, text) +#define _MACHO_SPECIALIZE_32(text...) _MACHO_SPECIALIZE(LC_SEGMENT, segment_command, section, nlist, 4, text) +#if ADDR64 +#define MACHO_SPECIALIZE(text...) _MACHO_SPECIALIZE_64(text) _MACHO_SPECIALIZE_32(text) +#define MACHO_SPECIALIZE_POINTER_SIZE(binary, text...) \ + if(b_pointer_size(binary) == 8) _MACHO_SPECIALIZE_64(text) else _MACHO_SPECIALIZE_32(text) +#else +#define MACHO_SPECIALIZE(text...) _MACHO_SPECIALIZE_32(text) +#define MACHO_SPECIALIZE_POINTER_SIZE(binary, text...) _MACHO_SPECIALIZE_32(text) +#endif + +struct mach_binary { + // this is unnecessary, don't use it + struct mach_header *hdr; + + // this stuff is _all_ symbols... + void *symtab; // either nlist or nlist_64 + uint32_t nsyms; + + // for b_sym (external stuff) + struct nlist *ext_symtab, *imp_symtab; + uint32_t ext_nsyms, imp_nsyms; + + // alternatively + struct dyld_info_command *dyld_info; + prange_t export_trie; + addr_t export_baseaddr; + + char *strtab; + uint32_t strsize; + const struct dysymtab_command *dysymtab; +}; + +__BEGIN_DECLS + +static inline struct mach_header *b_mach_hdr(const struct binary *binary) { + return (struct mach_header *) ((char *) binary->valid_range.start + binary->header_offset); +} + +__attribute__((pure)) range_t b_macho_segrange(const struct binary *binary, const char *segname); +__attribute__((pure)) range_t b_macho_sectrange(const struct binary *binary, const char *segname, const char *sectname); + +void b_prange_load_macho(struct binary *binary, prange_t range, size_t offset, const char *name); +void b_prange_load_macho_nosyms(struct binary *binary, prange_t range, size_t offset, const char *name); + +void b_load_macho(struct binary *binary, const char *filename); + +void *b_macho_nth_symbol(const struct binary *binary, uint32_t n); + +addr_t b_macho_reloc_base(const struct binary *binary); + +const char *convert_lc_str(const struct load_command *cmd, uint32_t offset); +__END_DECLS + diff --git a/data/mach-o/headers/arm_reloc.h b/data/mach-o/headers/arm_reloc.h new file mode 100644 index 0000000..2638d30 --- /dev/null +++ b/data/mach-o/headers/arm_reloc.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1999 Apple Computer, Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ +/* + * Relocation types used in the arm implementation. Relocation entries for + * things other than instructions use the same generic relocation as discribed + * in and their r_type is ARM_RELOC_VANILLA, one of the + * *_SECTDIFF or the *_PB_LA_PTR types. The rest of the relocation types are + * for instructions. Since they are for instructions the r_address field + * indicates the 32 bit instruction that the relocation is to be preformed on. + */ +enum reloc_type_arm +{ + ARM_RELOC_VANILLA, /* generic relocation as discribed above */ + ARM_RELOC_PAIR, /* the second relocation entry of a pair */ + ARM_RELOC_SECTDIFF, /* a PAIR follows with subtract symbol value */ + ARM_RELOC_LOCAL_SECTDIFF, /* like ARM_RELOC_SECTDIFF, but the symbol + referenced was local. */ + ARM_RELOC_PB_LA_PTR,/* prebound lazy pointer */ + ARM_RELOC_BR24, /* 24 bit branch displacement (to a word address) */ + ARM_THUMB_RELOC_BR22, /* 22 bit branch displacement (to a half-word + address) */ + ARM_THUMB_32BIT_BRANCH, /* obsolete - a thumb 32-bit branch instruction + possibly needing page-spanning branch workaround */ +}; diff --git a/data/mach-o/headers/fat.h b/data/mach-o/headers/fat.h new file mode 100644 index 0000000..e0d4e48 --- /dev/null +++ b/data/mach-o/headers/fat.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1999 Apple Computer, Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ +#ifndef _MACH_O_FAT_H_ +#define _MACH_O_FAT_H_ +/* + * This header file describes the structures of the file format for "fat" + * architecture specific file (wrapper design). At the begining of the file + * there is one fat_header structure followed by a number of fat_arch + * structures. For each architecture in the file, specified by a pair of + * cputype and cpusubtype, the fat_header describes the file offset, file + * size and alignment in the file of the architecture specific member. + * The padded bytes in the file to place each member on it's specific alignment + * are defined to be read as zeros and can be left as "holes" if the file system + * can support them as long as they read as zeros. + * + * All structures defined here are always written and read to/from disk + * in big-endian order. + */ + +/* + * is needed here for the cpu_type_t and cpu_subtype_t types + * and contains the constants for the possible values of these types. + */ + +#include + +#define FAT_MAGIC 0xcafebabe +#define FAT_CIGAM 0xbebafeca /* NXSwapLong(FAT_MAGIC) */ + +struct fat_header { + uint32_t magic; /* FAT_MAGIC */ + uint32_t nfat_arch; /* number of structs that follow */ +}; + +struct fat_arch { + int cputype; /* cpu specifier (int) */ + int cpusubtype; /* machine specifier (int) */ + uint32_t offset; /* file offset to this object file */ + uint32_t size; /* size of this object file */ + uint32_t align; /* alignment as a power of 2 */ +}; + +#endif /* _MACH_O_FAT_H_ */ diff --git a/data/mach-o/headers/loader.h b/data/mach-o/headers/loader.h new file mode 100644 index 0000000..4e75ead --- /dev/null +++ b/data/mach-o/headers/loader.h @@ -0,0 +1,1340 @@ +/* + * Copyright (c) 1999-2008 Apple Inc. All Rights Reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ +#ifndef _MACHO_LOADER_H_ +#define _MACHO_LOADER_H_ + +/* + * This file describes the format of mach object files. + */ +#include + +/* + * is needed here for the cpu_type_t and cpu_subtype_t types + * and contains the constants for the possible values of these types. + */ + +/* + * is needed here for the vm_prot_t type and contains the + * constants that are or'ed together for the possible values of this type. + */ + +/* + * is expected to define the flavors of the thread + * states and the structures of those flavors for each machine. + */ + +/* + * The 32-bit mach header appears at the very beginning of the object file for + * 32-bit architectures. + */ +struct mach_header { + uint32_t magic; /* mach magic number identifier */ + int cputype; /* cpu specifier */ + int cpusubtype; /* machine specifier */ + uint32_t filetype; /* type of file */ + uint32_t ncmds; /* number of load commands */ + uint32_t sizeofcmds; /* the size of all the load commands */ + uint32_t flags; /* flags */ +}; + +/* Constant for the magic field of the mach_header (32-bit architectures) */ +#define MH_MAGIC 0xfeedface /* the mach magic number */ +#define MH_CIGAM 0xcefaedfe /* NXSwapInt(MH_MAGIC) */ + +/* + * The 64-bit mach header appears at the very beginning of object files for + * 64-bit architectures. + */ +struct mach_header_64 { + uint32_t magic; /* mach magic number identifier */ + int cputype; /* cpu specifier */ + int cpusubtype; /* machine specifier */ + uint32_t filetype; /* type of file */ + uint32_t ncmds; /* number of load commands */ + uint32_t sizeofcmds; /* the size of all the load commands */ + uint32_t flags; /* flags */ + uint32_t reserved; /* reserved */ +}; + +/* Constant for the magic field of the mach_header_64 (64-bit architectures) */ +#define MH_MAGIC_64 0xfeedfacf /* the 64-bit mach magic number */ +#define MH_CIGAM_64 0xcffaedfe /* NXSwapInt(MH_MAGIC_64) */ + +/* + * The layout of the file depends on the filetype. For all but the MH_OBJECT + * file type the segments are padded out and aligned on a segment alignment + * boundary for efficient demand pageing. The MH_EXECUTE, MH_FVMLIB, MH_DYLIB, + * MH_DYLINKER and MH_BUNDLE file types also have the headers included as part + * of their first segment. + * + * The file type MH_OBJECT is a compact format intended as output of the + * assembler and input (and possibly output) of the link editor (the .o + * format). All sections are in one unnamed segment with no segment padding. + * This format is used as an executable format when the file is so small the + * segment padding greatly increases its size. + * + * The file type MH_PRELOAD is an executable format intended for things that + * are not executed under the kernel (proms, stand alones, kernels, etc). The + * format can be executed under the kernel but may demand paged it and not + * preload it before execution. + * + * A core file is in MH_CORE format and can be any in an arbritray legal + * Mach-O file. + * + * Constants for the filetype field of the mach_header + */ +#define MH_OBJECT 0x1 /* relocatable object file */ +#define MH_EXECUTE 0x2 /* demand paged executable file */ +#define MH_FVMLIB 0x3 /* fixed VM shared library file */ +#define MH_CORE 0x4 /* core file */ +#define MH_PRELOAD 0x5 /* preloaded executable file */ +#define MH_DYLIB 0x6 /* dynamically bound shared library */ +#define MH_DYLINKER 0x7 /* dynamic link editor */ +#define MH_BUNDLE 0x8 /* dynamically bound bundle file */ +#define MH_DYLIB_STUB 0x9 /* shared library stub for static */ + /* linking only, no section contents */ +#define MH_DSYM 0xa /* companion file with only debug */ + /* sections */ +#define MH_KEXT_BUNDLE 0xb /* x86_64 kexts */ + +/* Constants for the flags field of the mach_header */ +#define MH_NOUNDEFS 0x1 /* the object file has no undefined + references */ +#define MH_INCRLINK 0x2 /* the object file is the output of an + incremental link against a base file + and can't be link edited again */ +#define MH_DYLDLINK 0x4 /* the object file is input for the + dynamic linker and can't be staticly + link edited again */ +#define MH_BINDATLOAD 0x8 /* the object file's undefined + references are bound by the dynamic + linker when loaded. */ +#define MH_PREBOUND 0x10 /* the file has its dynamic undefined + references prebound. */ +#define MH_SPLIT_SEGS 0x20 /* the file has its read-only and + read-write segments split */ +#define MH_LAZY_INIT 0x40 /* the shared library init routine is + to be run lazily via catching memory + faults to its writeable segments + (obsolete) */ +#define MH_TWOLEVEL 0x80 /* the image is using two-level name + space bindings */ +#define MH_FORCE_FLAT 0x100 /* the executable is forcing all images + to use flat name space bindings */ +#define MH_NOMULTIDEFS 0x200 /* this umbrella guarantees no multiple + defintions of symbols in its + sub-images so the two-level namespace + hints can always be used. */ +#define MH_NOFIXPREBINDING 0x400 /* do not have dyld notify the + prebinding agent about this + executable */ +#define MH_PREBINDABLE 0x800 /* the binary is not prebound but can + have its prebinding redone. only used + when MH_PREBOUND is not set. */ +#define MH_ALLMODSBOUND 0x1000 /* indicates that this binary binds to + all two-level namespace modules of + its dependent libraries. only used + when MH_PREBINDABLE and MH_TWOLEVEL + are both set. */ +#define MH_SUBSECTIONS_VIA_SYMBOLS 0x2000/* safe to divide up the sections into + sub-sections via symbols for dead + code stripping */ +#define MH_CANONICAL 0x4000 /* the binary has been canonicalized + via the unprebind operation */ +#define MH_WEAK_DEFINES 0x8000 /* the final linked image contains + external weak symbols */ +#define MH_BINDS_TO_WEAK 0x10000 /* the final linked image uses + weak symbols */ + +#define MH_ALLOW_STACK_EXECUTION 0x20000/* When this bit is set, all stacks + in the task will be given stack + execution privilege. Only used in + MH_EXECUTE filetypes. */ +#define MH_DEAD_STRIPPABLE_DYLIB 0x400000 /* Only for use on dylibs. When + linking against a dylib that + has this bit set, the static linker + will automatically not create a + LC_LOAD_DYLIB load command to the + dylib if no symbols are being + referenced from the dylib. */ +#define MH_ROOT_SAFE 0x40000 /* When this bit is set, the binary + declares it is safe for use in + processes with uid zero */ + +#define MH_SETUID_SAFE 0x80000 /* When this bit is set, the binary + declares it is safe for use in + processes when issetugid() is true */ + +#define MH_NO_REEXPORTED_DYLIBS 0x100000 /* When this bit is set on a dylib, + the static linker does not need to + examine dependent dylibs to see + if any are re-exported */ +#define MH_PIE 0x200000 /* When this bit is set, the OS will + load the main executable at a + random address. Only used in + MH_EXECUTE filetypes. */ + +/* + * The load commands directly follow the mach_header. The total size of all + * of the commands is given by the sizeofcmds field in the mach_header. All + * load commands must have as their first two fields cmd and cmdsize. The cmd + * field is filled in with a constant for that command type. Each command type + * has a structure specifically for it. The cmdsize field is the size in bytes + * of the particular load command structure plus anything that follows it that + * is a part of the load command (i.e. section structures, strings, etc.). To + * advance to the next load command the cmdsize can be added to the offset or + * pointer of the current load command. The cmdsize for 32-bit architectures + * MUST be a multiple of 4 bytes and for 64-bit architectures MUST be a multiple + * of 8 bytes (these are forever the maximum alignment of any load commands). + * The padded bytes must be zero. All tables in the object file must also + * follow these rules so the file can be memory mapped. Otherwise the pointers + * to these tables will not work well or at all on some machines. With all + * padding zeroed like objects will compare byte for byte. + */ +struct load_command { + uint32_t cmd; /* type of load command */ + uint32_t cmdsize; /* total size of command in bytes */ +}; + +/* + * After MacOS X 10.1 when a new load command is added that is required to be + * understood by the dynamic linker for the image to execute properly the + * LC_REQ_DYLD bit will be or'ed into the load command constant. If the dynamic + * linker sees such a load command it it does not understand will issue a + * "unknown load command required for execution" error and refuse to use the + * image. Other load commands without this bit that are not understood will + * simply be ignored. + */ +#define LC_REQ_DYLD 0x80000000 + +/* Constants for the cmd field of all load commands, the type */ +#define LC_SEGMENT 0x1 /* segment of this file to be mapped */ +#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */ +#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */ +#define LC_THREAD 0x4 /* thread */ +#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */ +#define LC_LOADFVMLIB 0x6 /* load a specified fixed VM shared library */ +#define LC_IDFVMLIB 0x7 /* fixed VM shared library identification */ +#define LC_IDENT 0x8 /* object identification info (obsolete) */ +#define LC_FVMFILE 0x9 /* fixed VM file inclusion (internal use) */ +#define LC_PREPAGE 0xa /* prepage command (internal use) */ +#define LC_DYSYMTAB 0xb /* dynamic link-edit symbol table info */ +#define LC_LOAD_DYLIB 0xc /* load a dynamically linked shared library */ +#define LC_ID_DYLIB 0xd /* dynamically linked shared lib ident */ +#define LC_LOAD_DYLINKER 0xe /* load a dynamic linker */ +#define LC_ID_DYLINKER 0xf /* dynamic linker identification */ +#define LC_PREBOUND_DYLIB 0x10 /* modules prebound for a dynamically */ + /* linked shared library */ +#define LC_ROUTINES 0x11 /* image routines */ +#define LC_SUB_FRAMEWORK 0x12 /* sub framework */ +#define LC_SUB_UMBRELLA 0x13 /* sub umbrella */ +#define LC_SUB_CLIENT 0x14 /* sub client */ +#define LC_SUB_LIBRARY 0x15 /* sub library */ +#define LC_TWOLEVEL_HINTS 0x16 /* two-level namespace lookup hints */ +#define LC_PREBIND_CKSUM 0x17 /* prebind checksum */ + +/* + * load a dynamically linked shared library that is allowed to be missing + * (all symbols are weak imported). + */ +#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD) + +#define LC_SEGMENT_64 0x19 /* 64-bit segment of this file to be + mapped */ +#define LC_ROUTINES_64 0x1a /* 64-bit image routines */ +#define LC_UUID 0x1b /* the uuid */ +#define LC_RPATH (0x1c | LC_REQ_DYLD) /* runpath additions */ +#define LC_CODE_SIGNATURE 0x1d /* local of code signature */ +#define LC_SEGMENT_SPLIT_INFO 0x1e /* local of info to split segments */ +#define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD) /* load and re-export dylib */ +#define LC_LAZY_LOAD_DYLIB 0x20 /* delay load of dylib until first use */ +#define LC_ENCRYPTION_INFO 0x21 /* encrypted segment information */ +#define LC_DYLD_INFO 0x22 /* compressed dyld information */ +#define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */ +#define LC_LOAD_UPWARD_DYLIB (0x23 | LC_REQ_DYLD) /* load upward dylib */ + +/* + * A variable length string in a load command is represented by an lc_str + * union. The strings are stored just after the load command structure and + * the offset is from the start of the load command structure. The size + * of the string is reflected in the cmdsize field of the load command. + * Once again any padded bytes to bring the cmdsize field to a multiple + * of 4 bytes must be zero. + */ +union lc_str { + uint32_t offset; /* offset to the string */ +#ifndef __LP64__ + char *ptr; /* pointer to the string */ +#endif +}; + +/* + * The segment load command indicates that a part of this file is to be + * mapped into the task's address space. The size of this segment in memory, + * vmsize, maybe equal to or larger than the amount to map from this file, + * filesize. The file is mapped starting at fileoff to the beginning of + * the segment in memory, vmaddr. The rest of the memory of the segment, + * if any, is allocated zero fill on demand. The segment's maximum virtual + * memory protection and initial virtual memory protection are specified + * by the maxprot and initprot fields. If the segment has sections then the + * section structures directly follow the segment command and their size is + * reflected in cmdsize. + */ +struct segment_command { /* for 32-bit architectures */ + uint32_t cmd; /* LC_SEGMENT */ + uint32_t cmdsize; /* includes sizeof section structs */ + char segname[16]; /* segment name */ + uint32_t vmaddr; /* memory address of this segment */ + uint32_t vmsize; /* memory size of this segment */ + uint32_t fileoff; /* file offset of this segment */ + uint32_t filesize; /* amount to map from the file */ + int maxprot; /* maximum VM protection */ + int initprot; /* initial VM protection */ + uint32_t nsects; /* number of sections in segment */ + uint32_t flags; /* flags */ +}; + +/* + * The 64-bit segment load command indicates that a part of this file is to be + * mapped into a 64-bit task's address space. If the 64-bit segment has + * sections then section_64 structures directly follow the 64-bit segment + * command and their size is reflected in cmdsize. + */ +struct segment_command_64 { /* for 64-bit architectures */ + uint32_t cmd; /* LC_SEGMENT_64 */ + uint32_t cmdsize; /* includes sizeof section_64 structs */ + char segname[16]; /* segment name */ + uint64_t vmaddr; /* memory address of this segment */ + uint64_t vmsize; /* memory size of this segment */ + uint64_t fileoff; /* file offset of this segment */ + uint64_t filesize; /* amount to map from the file */ + int maxprot; /* maximum VM protection */ + int initprot; /* initial VM protection */ + uint32_t nsects; /* number of sections in segment */ + uint32_t flags; /* flags */ +}; + +/* Constants for the flags field of the segment_command */ +#define SG_HIGHVM 0x1 /* the file contents for this segment is for + the high part of the VM space, the low part + is zero filled (for stacks in core files) */ +#define SG_FVMLIB 0x2 /* this segment is the VM that is allocated by + a fixed VM library, for overlap checking in + the link editor */ +#define SG_NORELOC 0x4 /* this segment has nothing that was relocated + in it and nothing relocated to it, that is + it maybe safely replaced without relocation*/ +#define SG_PROTECTED_VERSION_1 0x8 /* This segment is protected. If the + segment starts at file offset 0, the + first page of the segment is not + protected. All other pages of the + segment are protected. */ + +/* + * A segment is made up of zero or more sections. Non-MH_OBJECT files have + * all of their segments with the proper sections in each, and padded to the + * specified segment alignment when produced by the link editor. The first + * segment of a MH_EXECUTE and MH_FVMLIB format file contains the mach_header + * and load commands of the object file before its first section. The zero + * fill sections are always last in their segment (in all formats). This + * allows the zeroed segment padding to be mapped into memory where zero fill + * sections might be. The gigabyte zero fill sections, those with the section + * type S_GB_ZEROFILL, can only be in a segment with sections of this type. + * These segments are then placed after all other segments. + * + * The MH_OBJECT format has all of its sections in one segment for + * compactness. There is no padding to a specified segment boundary and the + * mach_header and load commands are not part of the segment. + * + * Sections with the same section name, sectname, going into the same segment, + * segname, are combined by the link editor. The resulting section is aligned + * to the maximum alignment of the combined sections and is the new section's + * alignment. The combined sections are aligned to their original alignment in + * the combined section. Any padded bytes to get the specified alignment are + * zeroed. + * + * The format of the relocation entries referenced by the reloff and nreloc + * fields of the section structure for mach object files is described in the + * header file . + */ +struct section { /* for 32-bit architectures */ + char sectname[16]; /* name of this section */ + char segname[16]; /* segment this section goes in */ + uint32_t addr; /* memory address of this section */ + uint32_t size; /* size in bytes of this section */ + uint32_t offset; /* file offset of this section */ + uint32_t align; /* section alignment (power of 2) */ + uint32_t reloff; /* file offset of relocation entries */ + uint32_t nreloc; /* number of relocation entries */ + uint32_t flags; /* flags (section type and attributes)*/ + uint32_t reserved1; /* reserved (for offset or index) */ + uint32_t reserved2; /* reserved (for count or sizeof) */ +}; + +struct section_64 { /* for 64-bit architectures */ + char sectname[16]; /* name of this section */ + char segname[16]; /* segment this section goes in */ + uint64_t addr; /* memory address of this section */ + uint64_t size; /* size in bytes of this section */ + uint32_t offset; /* file offset of this section */ + uint32_t align; /* section alignment (power of 2) */ + uint32_t reloff; /* file offset of relocation entries */ + uint32_t nreloc; /* number of relocation entries */ + uint32_t flags; /* flags (section type and attributes)*/ + uint32_t reserved1; /* reserved (for offset or index) */ + uint32_t reserved2; /* reserved (for count or sizeof) */ + uint32_t reserved3; /* reserved */ +}; + +/* + * The flags field of a section structure is separated into two parts a section + * type and section attributes. The section types are mutually exclusive (it + * can only have one type) but the section attributes are not (it may have more + * than one attribute). + */ +#define SECTION_TYPE 0x000000ff /* 256 section types */ +#define SECTION_ATTRIBUTES 0xffffff00 /* 24 section attributes */ + +/* Constants for the type of a section */ +#define S_REGULAR 0x0 /* regular section */ +#define S_ZEROFILL 0x1 /* zero fill on demand section */ +#define S_CSTRING_LITERALS 0x2 /* section with only literal C strings*/ +#define S_4BYTE_LITERALS 0x3 /* section with only 4 byte literals */ +#define S_8BYTE_LITERALS 0x4 /* section with only 8 byte literals */ +#define S_LITERAL_POINTERS 0x5 /* section with only pointers to */ + /* literals */ +/* + * For the two types of symbol pointers sections and the symbol stubs section + * they have indirect symbol table entries. For each of the entries in the + * section the indirect symbol table entries, in corresponding order in the + * indirect symbol table, start at the index stored in the reserved1 field + * of the section structure. Since the indirect symbol table entries + * correspond to the entries in the section the number of indirect symbol table + * entries is inferred from the size of the section divided by the size of the + * entries in the section. For symbol pointers sections the size of the entries + * in the section is 4 bytes and for symbol stubs sections the byte size of the + * stubs is stored in the reserved2 field of the section structure. + */ +#define S_NON_LAZY_SYMBOL_POINTERS 0x6 /* section with only non-lazy + symbol pointers */ +#define S_LAZY_SYMBOL_POINTERS 0x7 /* section with only lazy symbol + pointers */ +#define S_SYMBOL_STUBS 0x8 /* section with only symbol + stubs, byte size of stub in + the reserved2 field */ +#define S_MOD_INIT_FUNC_POINTERS 0x9 /* section with only function + pointers for initialization*/ +#define S_MOD_TERM_FUNC_POINTERS 0xa /* section with only function + pointers for termination */ +#define S_COALESCED 0xb /* section contains symbols that + are to be coalesced */ +#define S_GB_ZEROFILL 0xc /* zero fill on demand section + (that can be larger than 4 + gigabytes) */ +#define S_INTERPOSING 0xd /* section with only pairs of + function pointers for + interposing */ +#define S_16BYTE_LITERALS 0xe /* section with only 16 byte + literals */ +#define S_DTRACE_DOF 0xf /* section contains + DTrace Object Format */ +#define S_LAZY_DYLIB_SYMBOL_POINTERS 0x10 /* section with only lazy + symbol pointers to lazy + loaded dylibs */ +/* + * Constants for the section attributes part of the flags field of a section + * structure. + */ +#define SECTION_ATTRIBUTES_USR 0xff000000 /* User setable attributes */ +#define S_ATTR_PURE_INSTRUCTIONS 0x80000000 /* section contains only true + machine instructions */ +#define S_ATTR_NO_TOC 0x40000000 /* section contains coalesced + symbols that are not to be + in a ranlib table of + contents */ +#define S_ATTR_STRIP_STATIC_SYMS 0x20000000 /* ok to strip static symbols + in this section in files + with the MH_DYLDLINK flag */ +#define S_ATTR_NO_DEAD_STRIP 0x10000000 /* no dead stripping */ +#define S_ATTR_LIVE_SUPPORT 0x08000000 /* blocks are live if they + reference live blocks */ +#define S_ATTR_SELF_MODIFYING_CODE 0x04000000 /* Used with i386 code stubs + written on by dyld */ +/* + * If a segment contains any sections marked with S_ATTR_DEBUG then all + * sections in that segment must have this attribute. No section other than + * a section marked with this attribute may reference the contents of this + * section. A section with this attribute may contain no symbols and must have + * a section type S_REGULAR. The static linker will not copy section contents + * from sections with this attribute into its output file. These sections + * generally contain DWARF debugging info. + */ +#define S_ATTR_DEBUG 0x02000000 /* a debug section */ +#define SECTION_ATTRIBUTES_SYS 0x00ffff00 /* system setable attributes */ +#define S_ATTR_SOME_INSTRUCTIONS 0x00000400 /* section contains some + machine instructions */ +#define S_ATTR_EXT_RELOC 0x00000200 /* section has external + relocation entries */ +#define S_ATTR_LOC_RELOC 0x00000100 /* section has local + relocation entries */ + + +/* + * The names of segments and sections in them are mostly meaningless to the + * link-editor. But there are few things to support traditional UNIX + * executables that require the link-editor and assembler to use some names + * agreed upon by convention. + * + * The initial protection of the "__TEXT" segment has write protection turned + * off (not writeable). + * + * The link-editor will allocate common symbols at the end of the "__common" + * section in the "__DATA" segment. It will create the section and segment + * if needed. + */ + +/* The currently known segment names and the section names in those segments */ + +#define SEG_PAGEZERO "__PAGEZERO" /* the pagezero segment which has no */ + /* protections and catches NULL */ + /* references for MH_EXECUTE files */ + + +#define SEG_TEXT "__TEXT" /* the tradition UNIX text segment */ +#define SECT_TEXT "__text" /* the real text part of the text */ + /* section no headers, and no padding */ +#define SECT_FVMLIB_INIT0 "__fvmlib_init0" /* the fvmlib initialization */ + /* section */ +#define SECT_FVMLIB_INIT1 "__fvmlib_init1" /* the section following the */ + /* fvmlib initialization */ + /* section */ + +#define SEG_DATA "__DATA" /* the tradition UNIX data segment */ +#define SECT_DATA "__data" /* the real initialized data section */ + /* no padding, no bss overlap */ +#define SECT_BSS "__bss" /* the real uninitialized data section*/ + /* no padding */ +#define SECT_COMMON "__common" /* the section common symbols are */ + /* allocated in by the link editor */ + +#define SEG_OBJC "__OBJC" /* objective-C runtime segment */ +#define SECT_OBJC_SYMBOLS "__symbol_table" /* symbol table */ +#define SECT_OBJC_MODULES "__module_info" /* module information */ +#define SECT_OBJC_STRINGS "__selector_strs" /* string table */ +#define SECT_OBJC_REFS "__selector_refs" /* string table */ + +#define SEG_ICON "__ICON" /* the icon segment */ +#define SECT_ICON_HEADER "__header" /* the icon headers */ +#define SECT_ICON_TIFF "__tiff" /* the icons in tiff format */ + +#define SEG_LINKEDIT "__LINKEDIT" /* the segment containing all structs */ + /* created and maintained by the link */ + /* editor. Created with -seglinkedit */ + /* option to ld(1) for MH_EXECUTE and */ + /* FVMLIB file types only */ + +#define SEG_UNIXSTACK "__UNIXSTACK" /* the unix stack segment */ + +#define SEG_IMPORT "__IMPORT" /* the segment for the self (dyld) */ + /* modifing code stubs that has read, */ + /* write and execute permissions */ + +/* + * Fixed virtual memory shared libraries are identified by two things. The + * target pathname (the name of the library as found for execution), and the + * minor version number. The address of where the headers are loaded is in + * header_addr. (THIS IS OBSOLETE and no longer supported). + */ +struct fvmlib { + union lc_str name; /* library's target pathname */ + uint32_t minor_version; /* library's minor version number */ + uint32_t header_addr; /* library's header address */ +}; + +/* + * A fixed virtual shared library (filetype == MH_FVMLIB in the mach header) + * contains a fvmlib_command (cmd == LC_IDFVMLIB) to identify the library. + * An object that uses a fixed virtual shared library also contains a + * fvmlib_command (cmd == LC_LOADFVMLIB) for each library it uses. + * (THIS IS OBSOLETE and no longer supported). + */ +struct fvmlib_command { + uint32_t cmd; /* LC_IDFVMLIB or LC_LOADFVMLIB */ + uint32_t cmdsize; /* includes pathname string */ + struct fvmlib fvmlib; /* the library identification */ +}; + +/* + * Dynamicly linked shared libraries are identified by two things. The + * pathname (the name of the library as found for execution), and the + * compatibility version number. The pathname must match and the compatibility + * number in the user of the library must be greater than or equal to the + * library being used. The time stamp is used to record the time a library was + * built and copied into user so it can be use to determined if the library used + * at runtime is exactly the same as used to built the program. + */ +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*/ +}; + +/* + * A dynamically linked shared library (filetype == MH_DYLIB in the mach header) + * contains a dylib_command (cmd == LC_ID_DYLIB) to identify the library. + * An object that uses a dynamically linked shared library also contains a + * dylib_command (cmd == LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, or + * LC_REEXPORT_DYLIB) for each library it uses. + */ +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 */ +}; + +/* + * A dynamically linked shared library may be a subframework of an umbrella + * framework. If so it will be linked with "-umbrella umbrella_name" where + * Where "umbrella_name" is the name of the umbrella framework. A subframework + * can only be linked against by its umbrella framework or other subframeworks + * that are part of the same umbrella framework. Otherwise the static link + * editor produces an error and states to link against the umbrella framework. + * The name of the umbrella framework for subframeworks is recorded in the + * following structure. + */ +struct sub_framework_command { + uint32_t cmd; /* LC_SUB_FRAMEWORK */ + uint32_t cmdsize; /* includes umbrella string */ + union lc_str umbrella; /* the umbrella framework name */ +}; + +/* + * For dynamically linked shared libraries that are subframework of an umbrella + * framework they can allow clients other than the umbrella framework or other + * subframeworks in the same umbrella framework. To do this the subframework + * is built with "-allowable_client client_name" and an LC_SUB_CLIENT load + * command is created for each -allowable_client flag. The client_name is + * usually a framework name. It can also be a name used for bundles clients + * where the bundle is built with "-client_name client_name". + */ +struct sub_client_command { + uint32_t cmd; /* LC_SUB_CLIENT */ + uint32_t cmdsize; /* includes client string */ + union lc_str client; /* the client name */ +}; + +/* + * A dynamically linked shared library may be a sub_umbrella of an umbrella + * framework. If so it will be linked with "-sub_umbrella umbrella_name" where + * Where "umbrella_name" is the name of the sub_umbrella framework. When + * staticly linking when -twolevel_namespace is in effect a twolevel namespace + * umbrella framework will only cause its subframeworks and those frameworks + * listed as sub_umbrella frameworks to be implicited linked in. Any other + * dependent dynamic libraries will not be linked it when -twolevel_namespace + * is in effect. The primary library recorded by the static linker when + * resolving a symbol in these libraries will be the umbrella framework. + * Zero or more sub_umbrella frameworks may be use by an umbrella framework. + * The name of a sub_umbrella framework is recorded in the following structure. + */ +struct sub_umbrella_command { + uint32_t cmd; /* LC_SUB_UMBRELLA */ + uint32_t cmdsize; /* includes sub_umbrella string */ + union lc_str sub_umbrella; /* the sub_umbrella framework name */ +}; + +/* + * A dynamically linked shared library may be a sub_library of another shared + * library. If so it will be linked with "-sub_library library_name" where + * Where "library_name" is the name of the sub_library shared library. When + * staticly linking when -twolevel_namespace is in effect a twolevel namespace + * shared library will only cause its subframeworks and those frameworks + * listed as sub_umbrella frameworks and libraries listed as sub_libraries to + * be implicited linked in. Any other dependent dynamic libraries will not be + * linked it when -twolevel_namespace is in effect. The primary library + * recorded by the static linker when resolving a symbol in these libraries + * will be the umbrella framework (or dynamic library). Zero or more sub_library + * shared libraries may be use by an umbrella framework or (or dynamic library). + * The name of a sub_library framework is recorded in the following structure. + * For example /usr/lib/libobjc_profile.A.dylib would be recorded as "libobjc". + */ +struct sub_library_command { + uint32_t cmd; /* LC_SUB_LIBRARY */ + uint32_t cmdsize; /* includes sub_library string */ + union lc_str sub_library; /* the sub_library name */ +}; + +/* + * A program (filetype == MH_EXECUTE) that is + * prebound to its dynamic libraries has one of these for each library that + * the static linker used in prebinding. It contains a bit vector for the + * modules in the library. The bits indicate which modules are bound (1) and + * which are not (0) from the library. The bit for module 0 is the low bit + * of the first byte. So the bit for the Nth module is: + * (linked_modules[N/8] >> N%8) & 1 + */ +struct prebound_dylib_command { + uint32_t cmd; /* LC_PREBOUND_DYLIB */ + uint32_t cmdsize; /* includes strings */ + union lc_str name; /* library's path name */ + uint32_t nmodules; /* number of modules in library */ + union lc_str linked_modules; /* bit vector of linked modules */ +}; + +/* + * A program that uses a dynamic linker contains a dylinker_command to identify + * the name of the dynamic linker (LC_LOAD_DYLINKER). And a dynamic linker + * contains a dylinker_command to identify the dynamic linker (LC_ID_DYLINKER). + * A file can have at most one of these. + */ +struct dylinker_command { + uint32_t cmd; /* LC_ID_DYLINKER or LC_LOAD_DYLINKER */ + uint32_t cmdsize; /* includes pathname string */ + union lc_str name; /* dynamic linker's path name */ +}; + +/* + * Thread commands contain machine-specific data structures suitable for + * use in the thread state primitives. The machine specific data structures + * follow the struct thread_command as follows. + * Each flavor of machine specific data structure is preceded by an unsigned + * long constant for the flavor of that data structure, an uint32_t + * that is the count of longs of the size of the state data structure and then + * the state data structure follows. This triple may be repeated for many + * flavors. The constants for the flavors, counts and state data structure + * definitions are expected to be in the header file . + * These machine specific data structures sizes must be multiples of + * 4 bytes The cmdsize reflects the total size of the thread_command + * and all of the sizes of the constants for the flavors, counts and state + * data structures. + * + * For executable objects that are unix processes there will be one + * thread_command (cmd == LC_UNIXTHREAD) created for it by the link-editor. + * This is the same as a LC_THREAD, except that a stack is automatically + * created (based on the shell's limit for the stack size). Command arguments + * and environment variables are copied onto that stack. + */ +struct thread_command { + uint32_t cmd; /* LC_THREAD or LC_UNIXTHREAD */ + uint32_t cmdsize; /* total size of this command */ + /* uint32_t flavor flavor of thread state */ + /* uint32_t count count of longs in thread state */ + /* struct XXX_thread_state state thread state for this flavor */ + /* ... */ +}; + +/* + * The routines command contains the address of the dynamic shared library + * initialization routine and an index into the module table for the module + * that defines the routine. Before any modules are used from the library the + * dynamic linker fully binds the module that defines the initialization routine + * and then calls it. This gets called before any module initialization + * routines (used for C++ static constructors) in the library. + */ +struct routines_command { /* for 32-bit architectures */ + uint32_t cmd; /* LC_ROUTINES */ + uint32_t cmdsize; /* total size of this command */ + uint32_t init_address; /* address of initialization routine */ + uint32_t init_module; /* index into the module table that */ + /* the init routine is defined in */ + uint32_t reserved1; + uint32_t reserved2; + uint32_t reserved3; + uint32_t reserved4; + uint32_t reserved5; + uint32_t reserved6; +}; + +/* + * The 64-bit routines command. Same use as above. + */ +struct routines_command_64 { /* for 64-bit architectures */ + uint32_t cmd; /* LC_ROUTINES_64 */ + uint32_t cmdsize; /* total size of this command */ + uint64_t init_address; /* address of initialization routine */ + uint64_t init_module; /* index into the module table that */ + /* the init routine is defined in */ + uint64_t reserved1; + uint64_t reserved2; + uint64_t reserved3; + uint64_t reserved4; + uint64_t reserved5; + uint64_t reserved6; +}; + +/* + * The symtab_command contains the offsets and sizes of the link-edit 4.3BSD + * "stab" style symbol table information as described in the header files + * and . + */ +struct symtab_command { + uint32_t cmd; /* LC_SYMTAB */ + uint32_t cmdsize; /* sizeof(struct symtab_command) */ + uint32_t symoff; /* symbol table offset */ + uint32_t nsyms; /* number of symbol table entries */ + uint32_t stroff; /* string table offset */ + uint32_t strsize; /* string table size in bytes */ +}; + +/* + * This is the second set of the symbolic information which is used to support + * the data structures for the dynamically link editor. + * + * The original set of symbolic information in the symtab_command which contains + * the symbol and string tables must also be present when this load command is + * present. When this load command is present the symbol table is organized + * into three groups of symbols: + * local symbols (static and debugging symbols) - grouped by module + * defined external symbols - grouped by module (sorted by name if not lib) + * undefined external symbols (sorted by name if MH_BINDATLOAD is not set, + * and in order the were seen by the static + * linker if MH_BINDATLOAD is set) + * In this load command there are offsets and counts to each of the three groups + * of symbols. + * + * This load command contains a the offsets and sizes of the following new + * symbolic information tables: + * table of contents + * module table + * reference symbol table + * indirect symbol table + * The first three tables above (the table of contents, module table and + * reference symbol table) are only present if the file is a dynamically linked + * shared library. For executable and object modules, which are files + * containing only one module, the information that would be in these three + * tables is determined as follows: + * table of contents - the defined external symbols are sorted by name + * module table - the file contains only one module so everything in the + * file is part of the module. + * reference symbol table - is the defined and undefined external symbols + * + * For dynamically linked shared library files this load command also contains + * offsets and sizes to the pool of relocation entries for all sections + * separated into two groups: + * external relocation entries + * local relocation entries + * For executable and object modules the relocation entries continue to hang + * off the section structures. + */ +struct dysymtab_command { + uint32_t cmd; /* LC_DYSYMTAB */ + uint32_t cmdsize; /* sizeof(struct dysymtab_command) */ + + /* + * The symbols indicated by symoff and nsyms of the LC_SYMTAB load command + * are grouped into the following three groups: + * local symbols (further grouped by the module they are from) + * defined external symbols (further grouped by the module they are from) + * undefined symbols + * + * The local symbols are used only for debugging. The dynamic binding + * process may have to use them to indicate to the debugger the local + * symbols for a module that is being bound. + * + * The last two groups are used by the dynamic binding process to do the + * binding (indirectly through the module table and the reference symbol + * table when this is a dynamically linked shared library file). + */ + uint32_t ilocalsym; /* index to local symbols */ + uint32_t nlocalsym; /* number of local symbols */ + + uint32_t iextdefsym;/* index to externally defined symbols */ + uint32_t nextdefsym;/* number of externally defined symbols */ + + uint32_t iundefsym; /* index to undefined symbols */ + uint32_t nundefsym; /* number of undefined symbols */ + + /* + * For the for the dynamic binding process to find which module a symbol + * is defined in the table of contents is used (analogous to the ranlib + * structure in an archive) which maps defined external symbols to modules + * they are defined in. This exists only in a dynamically linked shared + * library file. For executable and object modules the defined external + * symbols are sorted by name and is use as the table of contents. + */ + uint32_t tocoff; /* file offset to table of contents */ + uint32_t ntoc; /* number of entries in table of contents */ + + /* + * To support dynamic binding of "modules" (whole object files) the symbol + * table must reflect the modules that the file was created from. This is + * done by having a module table that has indexes and counts into the merged + * tables for each module. The module structure that these two entries + * refer to is described below. This exists only in a dynamically linked + * shared library file. For executable and object modules the file only + * contains one module so everything in the file belongs to the module. + */ + uint32_t modtaboff; /* file offset to module table */ + uint32_t nmodtab; /* number of module table entries */ + + /* + * To support dynamic module binding the module structure for each module + * indicates the external references (defined and undefined) each module + * makes. For each module there is an offset and a count into the + * reference symbol table for the symbols that the module references. + * This exists only in a dynamically linked shared library file. For + * executable and object modules the defined external symbols and the + * undefined external symbols indicates the external references. + */ + uint32_t extrefsymoff; /* offset to referenced symbol table */ + uint32_t nextrefsyms; /* number of referenced symbol table entries */ + + /* + * The sections that contain "symbol pointers" and "routine stubs" have + * indexes and (implied counts based on the size of the section and fixed + * size of the entry) into the "indirect symbol" table for each pointer + * and stub. For every section of these two types the index into the + * indirect symbol table is stored in the section header in the field + * reserved1. An indirect symbol table entry is simply a 32bit index into + * the symbol table to the symbol that the pointer or stub is referring to. + * The indirect symbol table is ordered to match the entries in the section. + */ + uint32_t indirectsymoff; /* file offset to the indirect symbol table */ + uint32_t nindirectsyms; /* number of indirect symbol table entries */ + + /* + * To support relocating an individual module in a library file quickly the + * external relocation entries for each module in the library need to be + * accessed efficiently. Since the relocation entries can't be accessed + * through the section headers for a library file they are separated into + * groups of local and external entries further grouped by module. In this + * case the presents of this load command who's extreloff, nextrel, + * locreloff and nlocrel fields are non-zero indicates that the relocation + * entries of non-merged sections are not referenced through the section + * structures (and the reloff and nreloc fields in the section headers are + * set to zero). + * + * Since the relocation entries are not accessed through the section headers + * this requires the r_address field to be something other than a section + * offset to identify the item to be relocated. In this case r_address is + * set to the offset from the vmaddr of the first LC_SEGMENT command. + * For MH_SPLIT_SEGS images r_address is set to the the offset from the + * vmaddr of the first read-write LC_SEGMENT command. + * + * The relocation entries are grouped by module and the module table + * entries have indexes and counts into them for the group of external + * relocation entries for that the module. + * + * For sections that are merged across modules there must not be any + * remaining external relocation entries for them (for merged sections + * remaining relocation entries must be local). + */ + uint32_t extreloff; /* offset to external relocation entries */ + uint32_t nextrel; /* number of external relocation entries */ + + /* + * All the local relocation entries are grouped together (they are not + * grouped by their module since they are only used if the object is moved + * from it staticly link edited address). + */ + uint32_t locreloff; /* offset to local relocation entries */ + uint32_t nlocrel; /* number of local relocation entries */ + +}; + +/* + * An indirect symbol table entry is simply a 32bit index into the symbol table + * to the symbol that the pointer or stub is refering to. Unless it is for a + * non-lazy symbol pointer section for a defined symbol which strip(1) as + * removed. In which case it has the value INDIRECT_SYMBOL_LOCAL. If the + * symbol was also absolute INDIRECT_SYMBOL_ABS is or'ed with that. + */ +#define INDIRECT_SYMBOL_LOCAL 0x80000000 +#define INDIRECT_SYMBOL_ABS 0x40000000 + + +/* a table of contents entry */ +struct dylib_table_of_contents { + uint32_t symbol_index; /* the defined external symbol + (index into the symbol table) */ + uint32_t module_index; /* index into the module table this symbol + is defined in */ +}; + +/* a module table entry */ +struct dylib_module { + uint32_t module_name; /* the module name (index into string table) */ + + uint32_t iextdefsym; /* index into externally defined symbols */ + uint32_t nextdefsym; /* number of externally defined symbols */ + uint32_t irefsym; /* index into reference symbol table */ + uint32_t nrefsym; /* number of reference symbol table entries */ + uint32_t ilocalsym; /* index into symbols for local symbols */ + uint32_t nlocalsym; /* number of local symbols */ + + uint32_t iextrel; /* index into external relocation entries */ + uint32_t nextrel; /* number of external relocation entries */ + + uint32_t iinit_iterm; /* low 16 bits are the index into the init + section, high 16 bits are the index into + the term section */ + uint32_t ninit_nterm; /* low 16 bits are the number of init section + entries, high 16 bits are the number of + term section entries */ + + uint32_t /* for this module address of the start of */ + objc_module_info_addr; /* the (__OBJC,__module_info) section */ + uint32_t /* for this module size of */ + objc_module_info_size; /* the (__OBJC,__module_info) section */ +}; + +/* a 64-bit module table entry */ +struct dylib_module_64 { + uint32_t module_name; /* the module name (index into string table) */ + + uint32_t iextdefsym; /* index into externally defined symbols */ + uint32_t nextdefsym; /* number of externally defined symbols */ + uint32_t irefsym; /* index into reference symbol table */ + uint32_t nrefsym; /* number of reference symbol table entries */ + uint32_t ilocalsym; /* index into symbols for local symbols */ + uint32_t nlocalsym; /* number of local symbols */ + + uint32_t iextrel; /* index into external relocation entries */ + uint32_t nextrel; /* number of external relocation entries */ + + uint32_t iinit_iterm; /* low 16 bits are the index into the init + section, high 16 bits are the index into + the term section */ + uint32_t ninit_nterm; /* low 16 bits are the number of init section + entries, high 16 bits are the number of + term section entries */ + + uint32_t /* for this module size of */ + objc_module_info_size; /* the (__OBJC,__module_info) section */ + uint64_t /* for this module address of the start of */ + objc_module_info_addr; /* the (__OBJC,__module_info) section */ +}; + +/* + * The entries in the reference symbol table are used when loading the module + * (both by the static and dynamic link editors) and if the module is unloaded + * or replaced. Therefore all external symbols (defined and undefined) are + * listed in the module's reference table. The flags describe the type of + * reference that is being made. The constants for the flags are defined in + * as they are also used for symbol table entries. + */ +struct dylib_reference { + uint32_t isym:24, /* index into the symbol table */ + flags:8; /* flags to indicate the type of reference */ +}; + +/* + * The twolevel_hints_command contains the offset and number of hints in the + * two-level namespace lookup hints table. + */ +struct twolevel_hints_command { + uint32_t cmd; /* LC_TWOLEVEL_HINTS */ + uint32_t cmdsize; /* sizeof(struct twolevel_hints_command) */ + uint32_t offset; /* offset to the hint table */ + uint32_t nhints; /* number of hints in the hint table */ +}; + +/* + * The entries in the two-level namespace lookup hints table are twolevel_hint + * structs. These provide hints to the dynamic link editor where to start + * looking for an undefined symbol in a two-level namespace image. The + * isub_image field is an index into the sub-images (sub-frameworks and + * sub-umbrellas list) that made up the two-level image that the undefined + * symbol was found in when it was built by the static link editor. If + * isub-image is 0 the the symbol is expected to be defined in library and not + * in the sub-images. If isub-image is non-zero it is an index into the array + * of sub-images for the umbrella with the first index in the sub-images being + * 1. The array of sub-images is the ordered list of sub-images of the umbrella + * that would be searched for a symbol that has the umbrella recorded as its + * primary library. The table of contents index is an index into the + * library's table of contents. This is used as the starting point of the + * binary search or a directed linear search. + */ +struct twolevel_hint { + uint32_t + isub_image:8, /* index into the sub images */ + itoc:24; /* index into the table of contents */ +}; + +/* + * The prebind_cksum_command contains the value of the original check sum for + * prebound files or zero. When a prebound file is first created or modified + * for other than updating its prebinding information the value of the check sum + * is set to zero. When the file has it prebinding re-done and if the value of + * the check sum is zero the original check sum is calculated and stored in + * cksum field of this load command in the output file. If when the prebinding + * is re-done and the cksum field is non-zero it is left unchanged from the + * input file. + */ +struct prebind_cksum_command { + uint32_t cmd; /* LC_PREBIND_CKSUM */ + uint32_t cmdsize; /* sizeof(struct prebind_cksum_command) */ + uint32_t cksum; /* the check sum or zero */ +}; + +/* + * The uuid load command contains a single 128-bit unique random number that + * identifies an object produced by the static link editor. + */ +struct uuid_command { + uint32_t cmd; /* LC_UUID */ + uint32_t cmdsize; /* sizeof(struct uuid_command) */ + uint8_t uuid[16]; /* the 128-bit uuid */ +}; + +/* + * The rpath_command contains a path which at runtime should be added to + * the current run path used to find @rpath prefixed dylibs. + */ +struct rpath_command { + uint32_t cmd; /* LC_RPATH */ + uint32_t cmdsize; /* includes string */ + union lc_str path; /* path to add to run path */ +}; + +/* + * The linkedit_data_command contains the offsets and sizes of a blob + * of data in the __LINKEDIT segment. + */ +struct linkedit_data_command { + uint32_t cmd; /* LC_CODE_SIGNATURE or LC_SEGMENT_SPLIT_INFO */ + uint32_t cmdsize; /* sizeof(struct linkedit_data_command) */ + uint32_t dataoff; /* file offset of data in __LINKEDIT segment */ + uint32_t datasize; /* file size of data in __LINKEDIT segment */ +}; + +/* + * The encryption_info_command contains the file offset and size of an + * of an encrypted segment. + */ +struct encryption_info_command { + uint32_t cmd; /* LC_ENCRYPTION_INFO */ + uint32_t cmdsize; /* sizeof(struct encryption_info_command) */ + uint32_t cryptoff; /* file offset of encrypted range */ + uint32_t cryptsize; /* file size of encrypted range */ + uint32_t cryptid; /* which enryption system, + 0 means not-encrypted yet */ +}; + +/* + * The dyld_info_command contains the file offsets and sizes of + * the new compressed form of the information dyld needs to + * load the image. This information is used by dyld on Mac OS X + * 10.6 and later. All information pointed to by this command + * is encoded using byte streams, so no endian swapping is needed + * to interpret it. + */ +struct dyld_info_command { + uint32_t cmd; /* LC_DYLD_INFO or LC_DYLD_INFO_ONLY */ + uint32_t cmdsize; /* sizeof(struct dyld_info_command) */ + + /* + * Dyld rebases an image whenever dyld loads it at an address different + * from its preferred address. The rebase information is a stream + * of byte sized opcodes whose symbolic names start with REBASE_OPCODE_. + * Conceptually the rebase information is a table of tuples: + * + * The opcodes are a compressed way to encode the table by only + * encoding when a column changes. In addition simple patterns + * like "every n'th offset for m times" can be encoded in a few + * bytes. + */ + uint32_t rebase_off; /* file offset to rebase info */ + uint32_t rebase_size; /* size of rebase info */ + + /* + * Dyld binds an image during the loading process, if the image + * requires any pointers to be initialized to symbols in other images. + * The bind information is a stream of byte sized + * opcodes whose symbolic names start with BIND_OPCODE_. + * Conceptually the bind information is a table of tuples: + * + * The opcodes are a compressed way to encode the table by only + * encoding when a column changes. In addition simple patterns + * like for runs of pointers initialzed to the same value can be + * encoded in a few bytes. + */ + uint32_t bind_off; /* file offset to binding info */ + uint32_t bind_size; /* size of binding info */ + + /* + * Some C++ programs require dyld to unique symbols so that all + * images in the process use the same copy of some code/data. + * This step is done after binding. The content of the weak_bind + * info is an opcode stream like the bind_info. But it is sorted + * alphabetically by symbol name. This enable dyld to walk + * all images with weak binding information in order and look + * for collisions. If there are no collisions, dyld does + * no updating. That means that some fixups are also encoded + * in the bind_info. For instance, all calls to "operator new" + * are first bound to libstdc++.dylib using the information + * in bind_info. Then if some image overrides operator new + * that is detected when the weak_bind information is processed + * and the call to operator new is then rebound. + */ + uint32_t weak_bind_off; /* file offset to weak binding info */ + uint32_t weak_bind_size; /* size of weak binding info */ + + /* + * Some uses of external symbols do not need to be bound immediately. + * Instead they can be lazily bound on first use. The lazy_bind + * are contains a stream of BIND opcodes to bind all lazy symbols. + * Normal use is that dyld ignores the lazy_bind section when + * loading an image. Instead the static linker arranged for the + * lazy pointer to initially point to a helper function which + * pushes the offset into the lazy_bind area for the symbol + * needing to be bound, then jumps to dyld which simply adds + * the offset to lazy_bind_off to get the information on what + * to bind. + */ + uint32_t lazy_bind_off; /* file offset to lazy binding info */ + uint32_t lazy_bind_size; /* size of lazy binding infs */ + + /* + * The symbols exported by a dylib are encoded in a trie. This + * is a compact representation that factors out common prefixes. + * It also reduces LINKEDIT pages in RAM because it encodes all + * information (name, address, flags) in one small, contiguous range. + * The export area is a stream of nodes. The first node sequentially + * is the start node for the trie. + * + * Nodes for a symbol start with a byte that is the length of + * the exported symbol information for the string so far. + * If there is no exported symbol, the byte is zero. If there + * is exported info, it follows the length byte. The exported + * info normally consists of a flags and offset both encoded + * in uleb128. The offset is location of the content named + * by the symbol. It is the offset from the mach_header for + * the image. + * + * After the initial byte and optional exported symbol information + * is a byte of how many edges (0-255) that this node has leaving + * it, followed by each edge. + * Each edge is a zero terminated cstring of the addition chars + * in the symbol, followed by a uleb128 offset for the node that + * edge points to. + * + */ + uint32_t export_off; /* file offset to lazy binding info */ + uint32_t export_size; /* size of lazy binding infs */ +}; + +/* + * The following are used to encode rebasing information + */ +#define REBASE_TYPE_POINTER 1 +#define REBASE_TYPE_TEXT_ABSOLUTE32 2 +#define REBASE_TYPE_TEXT_PCREL32 3 + +#define REBASE_OPCODE_MASK 0xF0 +#define REBASE_IMMEDIATE_MASK 0x0F +#define REBASE_OPCODE_DONE 0x00 +#define REBASE_OPCODE_SET_TYPE_IMM 0x10 +#define REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x20 +#define REBASE_OPCODE_ADD_ADDR_ULEB 0x30 +#define REBASE_OPCODE_ADD_ADDR_IMM_SCALED 0x40 +#define REBASE_OPCODE_DO_REBASE_IMM_TIMES 0x50 +#define REBASE_OPCODE_DO_REBASE_ULEB_TIMES 0x60 +#define REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB 0x70 +#define REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB 0x80 + + +/* + * The following are used to encode binding information + */ +#define BIND_TYPE_POINTER 1 +#define BIND_TYPE_TEXT_ABSOLUTE32 2 +#define BIND_TYPE_TEXT_PCREL32 3 + +#define BIND_SPECIAL_DYLIB_SELF 0 +#define BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE -1 +#define BIND_SPECIAL_DYLIB_FLAT_LOOKUP -2 + +#define BIND_SYMBOL_FLAGS_WEAK_IMPORT 0x1 +#define BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION 0x8 + +#define BIND_OPCODE_MASK 0xF0 +#define BIND_IMMEDIATE_MASK 0x0F +#define BIND_OPCODE_DONE 0x00 +#define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10 +#define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20 +#define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30 +#define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40 +#define BIND_OPCODE_SET_TYPE_IMM 0x50 +#define BIND_OPCODE_SET_ADDEND_SLEB 0x60 +#define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70 +#define BIND_OPCODE_ADD_ADDR_ULEB 0x80 +#define BIND_OPCODE_DO_BIND 0x90 +#define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xA0 +#define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xB0 +#define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xC0 + + +/* + * The following are used on the flags byte of a terminal node + * in the export information. + */ +#define EXPORT_SYMBOL_FLAGS_KIND_MASK 0x03 +#define EXPORT_SYMBOL_FLAGS_KIND_REGULAR 0x00 +#define EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL 0x01 +#define EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION 0x04 +#define EXPORT_SYMBOL_FLAGS_INDIRECT_DEFINITION 0x08 +#define EXPORT_SYMBOL_FLAGS_HAS_SPECIALIZATIONS 0x10 + +/* + * The symseg_command contains the offset and size of the GNU style + * symbol table information as described in the header file . + * The symbol roots of the symbol segments must also be aligned properly + * in the file. So the requirement of keeping the offsets aligned to a + * multiple of a 4 bytes translates to the length field of the symbol + * roots also being a multiple of a long. Also the padding must again be + * zeroed. (THIS IS OBSOLETE and no longer supported). + */ +struct symseg_command { + uint32_t cmd; /* LC_SYMSEG */ + uint32_t cmdsize; /* sizeof(struct symseg_command) */ + uint32_t offset; /* symbol segment offset */ + uint32_t size; /* symbol segment size in bytes */ +}; + +/* + * The ident_command contains a free format string table following the + * ident_command structure. The strings are null terminated and the size of + * the command is padded out with zero bytes to a multiple of 4 bytes/ + * (THIS IS OBSOLETE and no longer supported). + */ +struct ident_command { + uint32_t cmd; /* LC_IDENT */ + uint32_t cmdsize; /* strings that follow this command */ +}; + +/* + * The fvmfile_command contains a reference to a file to be loaded at the + * specified virtual address. (Presently, this command is reserved for + * internal use. The kernel ignores this command when loading a program into + * memory). + */ +struct fvmfile_command { + uint32_t cmd; /* LC_FVMFILE */ + uint32_t cmdsize; /* includes pathname string */ + union lc_str name; /* files pathname */ + uint32_t header_addr; /* files virtual address */ +}; + +#endif /* _MACHO_LOADER_H_ */ diff --git a/data/mach-o/headers/nlist.h b/data/mach-o/headers/nlist.h new file mode 100644 index 0000000..868ec20 --- /dev/null +++ b/data/mach-o/headers/nlist.h @@ -0,0 +1,302 @@ +/* + * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ +#ifndef _MACHO_NLIST_H_ +#define _MACHO_NLIST_H_ +/* $NetBSD: nlist.h,v 1.5 1994/10/26 00:56:11 cgd Exp $ */ + +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * (c) UNIX System Laboratories, Inc. + * All or some portions of this file are derived from material licensed + * to the University of California by American Telephone and Telegraph + * Co. or Unix System Laboratories, Inc. and are reproduced herein with + * the permission of UNIX System Laboratories, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)nlist.h 8.2 (Berkeley) 1/21/94 + */ +#include + +/* + * Format of a symbol table entry of a Mach-O file for 32-bit architectures. + * Modified from the BSD format. The modifications from the original format + * were changing n_other (an unused field) to n_sect and the addition of the + * N_SECT type. These modifications are required to support symbols in a larger + * number of sections not just the three sections (text, data and bss) in a BSD + * file. + */ +struct nlist { + union { +#ifndef __LP64__ + char *n_name; /* for use when in-core */ +#endif + int32_t n_strx; /* index into the string table */ + } n_un; + uint8_t n_type; /* type flag, see below */ + uint8_t n_sect; /* section number or NO_SECT */ + int16_t n_desc; /* see */ + uint32_t n_value; /* value of this symbol (or stab offset) */ +}; + +/* + * This is the symbol table entry structure for 64-bit architectures. + */ +struct nlist_64 { + union { + uint32_t n_strx; /* index into the string table */ + } n_un; + uint8_t n_type; /* type flag, see below */ + uint8_t n_sect; /* section number or NO_SECT */ + uint16_t n_desc; /* see */ + uint64_t n_value; /* value of this symbol (or stab offset) */ +}; + +/* + * Symbols with a index into the string table of zero (n_un.n_strx == 0) are + * defined to have a null, "", name. Therefore all string indexes to non null + * names must not have a zero string index. This is bit historical information + * that has never been well documented. + */ + +/* + * The n_type field really contains four fields: + * unsigned char N_STAB:3, + * N_PEXT:1, + * N_TYPE:3, + * N_EXT:1; + * which are used via the following masks. + */ +#define N_STAB 0xe0 /* if any of these bits set, a symbolic debugging entry */ +#define N_PEXT 0x10 /* private external symbol bit */ +#define N_TYPE 0x0e /* mask for the type bits */ +#define N_EXT 0x01 /* external symbol bit, set for external symbols */ + +/* + * Only symbolic debugging entries have some of the N_STAB bits set and if any + * of these bits are set then it is a symbolic debugging entry (a stab). In + * which case then the values of the n_type field (the entire field) are given + * in + */ + +/* + * Values for N_TYPE bits of the n_type field. + */ +#define N_UNDF 0x0 /* undefined, n_sect == NO_SECT */ +#define N_ABS 0x2 /* absolute, n_sect == NO_SECT */ +#define N_SECT 0xe /* defined in section number n_sect */ +#define N_PBUD 0xc /* prebound undefined (defined in a dylib) */ +#define N_INDR 0xa /* indirect */ + +/* + * If the type is N_INDR then the symbol is defined to be the same as another + * symbol. In this case the n_value field is an index into the string table + * of the other symbol's name. When the other symbol is defined then they both + * take on the defined type and value. + */ + +/* + * If the type is N_SECT then the n_sect field contains an ordinal of the + * section the symbol is defined in. The sections are numbered from 1 and + * refer to sections in order they appear in the load commands for the file + * they are in. This means the same ordinal may very well refer to different + * sections in different files. + * + * The n_value field for all symbol table entries (including N_STAB's) gets + * updated by the link editor based on the value of it's n_sect field and where + * the section n_sect references gets relocated. If the value of the n_sect + * field is NO_SECT then it's n_value field is not changed by the link editor. + */ +#define NO_SECT 0 /* symbol is not in any section */ +#define MAX_SECT 255 /* 1 thru 255 inclusive */ + +/* + * Common symbols are represented by undefined (N_UNDF) external (N_EXT) types + * who's values (n_value) are non-zero. In which case the value of the n_value + * field is the size (in bytes) of the common symbol. The n_sect field is set + * to NO_SECT. The alignment of a common symbol may be set as a power of 2 + * between 2^1 and 2^15 as part of the n_desc field using the macros below. If + * the alignment is not set (a value of zero) then natural alignment based on + * the size is used. + */ +#define GET_COMM_ALIGN(n_desc) (((n_desc) >> 8) & 0x0f) +#define SET_COMM_ALIGN(n_desc,align) \ + (n_desc) = (((n_desc) & 0xf0ff) | (((align) & 0x0f) << 8)) + +/* + * To support the lazy binding of undefined symbols in the dynamic link-editor, + * the undefined symbols in the symbol table (the nlist structures) are marked + * with the indication if the undefined reference is a lazy reference or + * non-lazy reference. If both a non-lazy reference and a lazy reference is + * made to the same symbol the non-lazy reference takes precedence. A reference + * is lazy only when all references to that symbol are made through a symbol + * pointer in a lazy symbol pointer section. + * + * The implementation of marking nlist structures in the symbol table for + * undefined symbols will be to use some of the bits of the n_desc field as a + * reference type. The mask REFERENCE_TYPE will be applied to the n_desc field + * of an nlist structure for an undefined symbol to determine the type of + * undefined reference (lazy or non-lazy). + * + * The constants for the REFERENCE FLAGS are propagated to the reference table + * in a shared library file. In that case the constant for a defined symbol, + * REFERENCE_FLAG_DEFINED, is also used. + */ +/* Reference type bits of the n_desc field of undefined symbols */ +#define REFERENCE_TYPE 0x7 +/* types of references */ +#define REFERENCE_FLAG_UNDEFINED_NON_LAZY 0 +#define REFERENCE_FLAG_UNDEFINED_LAZY 1 +#define REFERENCE_FLAG_DEFINED 2 +#define REFERENCE_FLAG_PRIVATE_DEFINED 3 +#define REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY 4 +#define REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY 5 + +/* + * To simplify stripping of objects that use are used with the dynamic link + * editor, the static link editor marks the symbols defined an object that are + * referenced by a dynamicly bound object (dynamic shared libraries, bundles). + * With this marking strip knows not to strip these symbols. + */ +#define REFERENCED_DYNAMICALLY 0x0010 + +/* + * For images created by the static link editor with the -twolevel_namespace + * option in effect the flags field of the mach header is marked with + * MH_TWOLEVEL. And the binding of the undefined references of the image are + * determined by the static link editor. Which library an undefined symbol is + * bound to is recorded by the static linker in the high 8 bits of the n_desc + * field using the SET_LIBRARY_ORDINAL macro below. The ordinal recorded + * references the libraries listed in the Mach-O's LC_LOAD_DYLIB load commands + * in the order they appear in the headers. The library ordinals start from 1. + * For a dynamic library that is built as a two-level namespace image the + * undefined references from module defined in another use the same nlist struct + * an in that case SELF_LIBRARY_ORDINAL is used as the library ordinal. For + * defined symbols in all images they also must have the library ordinal set to + * SELF_LIBRARY_ORDINAL. The EXECUTABLE_ORDINAL refers to the executable + * image for references from plugins that refer to the executable that loads + * them. + * + * The DYNAMIC_LOOKUP_ORDINAL is for undefined symbols in a two-level namespace + * image that are looked up by the dynamic linker with flat namespace semantics. + * This ordinal was added as a feature in Mac OS X 10.3 by reducing the + * value of MAX_LIBRARY_ORDINAL by one. So it is legal for existing binaries + * or binaries built with older tools to have 0xfe (254) dynamic libraries. In + * this case the ordinal value 0xfe (254) must be treated as a library ordinal + * for compatibility. + */ +#define GET_LIBRARY_ORDINAL(n_desc) (((n_desc) >> 8) & 0xff) +#define SET_LIBRARY_ORDINAL(n_desc,ordinal) \ + (n_desc) = (((n_desc) & 0x00ff) | (((ordinal) & 0xff) << 8)) +#define SELF_LIBRARY_ORDINAL 0x0 +#define MAX_LIBRARY_ORDINAL 0xfd +#define DYNAMIC_LOOKUP_ORDINAL 0xfe +#define EXECUTABLE_ORDINAL 0xff + +/* + * The bit 0x0020 of the n_desc field is used for two non-overlapping purposes + * and has two different symbolic names, N_NO_DEAD_STRIP and N_DESC_DISCARDED. + */ + +/* + * The N_NO_DEAD_STRIP bit of the n_desc field only ever appears in a + * relocatable .o file (MH_OBJECT filetype). And is used to indicate to the + * static link editor it is never to dead strip the symbol. + */ +#define N_NO_DEAD_STRIP 0x0020 /* symbol is not to be dead stripped */ + +/* + * The N_DESC_DISCARDED bit of the n_desc field never appears in linked image. + * But is used in very rare cases by the dynamic link editor to mark an in + * memory symbol as discared and longer used for linking. + */ +#define N_DESC_DISCARDED 0x0020 /* symbol is discarded */ + +/* + * The N_WEAK_REF bit of the n_desc field indicates to the dynamic linker that + * the undefined symbol is allowed to be missing and is to have the address of + * zero when missing. + */ +#define N_WEAK_REF 0x0040 /* symbol is weak referenced */ + +/* + * The N_WEAK_DEF bit of the n_desc field indicates to the static and dynamic + * linkers that the symbol definition is weak, allowing a non-weak symbol to + * also be used which causes the weak definition to be discared. Currently this + * is only supported for symbols in coalesed sections. + */ +#define N_WEAK_DEF 0x0080 /* coalesed symbol is a weak definition */ + +/* + * The N_REF_TO_WEAK bit of the n_desc field indicates to the dynamic linker + * that the undefined symbol should be resolved using flat namespace searching. + */ +#define N_REF_TO_WEAK 0x0080 /* reference to a weak symbol */ + +/* + * The N_ARM_THUMB_DEF bit of the n_desc field indicates that the symbol is + * a defintion of a Thumb function. + */ +#define N_ARM_THUMB_DEF 0x0008 /* symbol is a Thumb function (ARM) */ + +#ifndef __STRICT_BSD__ +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +/* + * The function nlist(3) from the C library. + */ +extern int nlist (const char *filename, struct nlist *list); +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __STRICT_BSD__ */ + +#endif /* _MACHO_LIST_H_ */ diff --git a/data/mach-o/headers/reloc.h b/data/mach-o/headers/reloc.h new file mode 100644 index 0000000..e36f4f7 --- /dev/null +++ b/data/mach-o/headers/reloc.h @@ -0,0 +1,202 @@ +/* + * Copyright (c) 1999 Apple Computer, Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ +/* $NetBSD: exec.h,v 1.6 1994/10/27 04:16:05 cgd Exp $ */ + +/* + * Copyright (c) 1993 Christopher G. Demetriou + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _MACHO_RELOC_H_ +#define _MACHO_RELOC_H_ +#include + +/* + * Format of a relocation entry of a Mach-O file. Modified from the 4.3BSD + * format. The modifications from the original format were changing the value + * of the r_symbolnum field for "local" (r_extern == 0) relocation entries. + * This modification is required to support symbols in an arbitrary number of + * sections not just the three sections (text, data and bss) in a 4.3BSD file. + * Also the last 4 bits have had the r_type tag added to them. + */ +struct relocation_info { + int32_t r_address; /* offset in the section to what is being + relocated */ + uint32_t r_symbolnum:24, /* symbol index if r_extern == 1 or section + ordinal if r_extern == 0 */ + r_pcrel:1, /* was relocated pc relative already */ + r_length:2, /* 0=byte, 1=word, 2=long, 3=quad */ + r_extern:1, /* does not include value of sym referenced */ + r_type:4; /* if not 0, machine specific relocation type */ +}; +#define R_ABS 0 /* absolute relocation type for Mach-O files */ + +/* + * The r_address is not really the address as it's name indicates but an offset. + * In 4.3BSD a.out objects this offset is from the start of the "segment" for + * which relocation entry is for (text or data). For Mach-O object files it is + * also an offset but from the start of the "section" for which the relocation + * entry is for. See comments in about the r_address feild + * in images for used with the dynamic linker. + * + * In 4.3BSD a.out objects if r_extern is zero then r_symbolnum is an ordinal + * for the segment the symbol being relocated is in. These ordinals are the + * symbol types N_TEXT, N_DATA, N_BSS or N_ABS. In Mach-O object files these + * ordinals refer to the sections in the object file in the order their section + * structures appear in the headers of the object file they are in. The first + * section has the ordinal 1, the second 2, and so on. This means that the + * same ordinal in two different object files could refer to two different + * sections. And further could have still different ordinals when combined + * by the link-editor. The value R_ABS is used for relocation entries for + * absolute symbols which need no further relocation. + */ + +/* + * For RISC machines some of the references are split across two instructions + * and the instruction does not contain the complete value of the reference. + * In these cases a second, or paired relocation entry, follows each of these + * relocation entries, using a PAIR r_type, which contains the other part of the + * reference not contained in the instruction. This other part is stored in the + * pair's r_address field. The exact number of bits of the other part of the + * reference store in the r_address field is dependent on the particular + * relocation type for the particular architecture. + */ + +/* + * To make scattered loading by the link editor work correctly "local" + * relocation entries can't be used when the item to be relocated is the value + * of a symbol plus an offset (where the resulting expresion is outside the + * block the link editor is moving, a blocks are divided at symbol addresses). + * In this case. where the item is a symbol value plus offset, the link editor + * needs to know more than just the section the symbol was defined. What is + * needed is the actual value of the symbol without the offset so it can do the + * relocation correctly based on where the value of the symbol got relocated to + * not the value of the expression (with the offset added to the symbol value). + * So for the NeXT 2.0 release no "local" relocation entries are ever used when + * there is a non-zero offset added to a symbol. The "external" and "local" + * relocation entries remain unchanged. + * + * The implemention is quite messy given the compatibility with the existing + * relocation entry format. The ASSUMPTION is that a section will never be + * bigger than 2**24 - 1 (0x00ffffff or 16,777,215) bytes. This assumption + * allows the r_address (which is really an offset) to fit in 24 bits and high + * bit of the r_address field in the relocation_info structure to indicate + * it is really a scattered_relocation_info structure. Since these are only + * used in places where "local" relocation entries are used and not where + * "external" relocation entries are used the r_extern field has been removed. + * + * For scattered loading to work on a RISC machine where some of the references + * are split across two instructions the link editor needs to be assured that + * each reference has a unique 32 bit reference (that more than one reference is + * NOT sharing the same high 16 bits for example) so it move each referenced + * item independent of each other. Some compilers guarantees this but the + * compilers don't so scattered loading can be done on those that do guarantee + * this. + */ +#if defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__) +/* + * The reason for the ifdef's of __BIG_ENDIAN__ and __LITTLE_ENDIAN__ are that + * when stattered relocation entries were added the mistake of using a mask + * against a structure that is made up of bit fields was used. To make this + * design work this structure must be laid out in memory the same way so the + * mask can be applied can check the same bit each time (r_scattered). + */ +#endif /* defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__) */ +#define R_SCATTERED 0x80000000 /* mask to be applied to the r_address field + of a relocation_info structure to tell that + is is really a scattered_relocation_info + stucture */ +struct scattered_relocation_info { +#ifdef __BIG_ENDIAN__ + uint32_t r_scattered:1, /* 1=scattered, 0=non-scattered (see above) */ + r_pcrel:1, /* was relocated pc relative already */ + r_length:2, /* 0=byte, 1=word, 2=long, 3=quad */ + r_type:4, /* if not 0, machine specific relocation type */ + r_address:24; /* offset in the section to what is being + relocated */ + int32_t r_value; /* the value the item to be relocated is + refering to (without any offset added) */ +#endif /* __BIG_ENDIAN__ */ +#ifdef __LITTLE_ENDIAN__ + uint32_t + r_address:24, /* offset in the section to what is being + relocated */ + r_type:4, /* if not 0, machine specific relocation type */ + r_length:2, /* 0=byte, 1=word, 2=long, 3=quad */ + r_pcrel:1, /* was relocated pc relative already */ + r_scattered:1; /* 1=scattered, 0=non-scattered (see above) */ + int32_t r_value; /* the value the item to be relocated is + refering to (without any offset added) */ +#endif /* __LITTLE_ENDIAN__ */ +}; + +/* + * Relocation types used in a generic implementation. Relocation entries for + * normal things use the generic relocation as discribed above and their r_type + * is GENERIC_RELOC_VANILLA (a value of zero). + * + * Another type of generic relocation, GENERIC_RELOC_SECTDIFF, is to support + * the difference of two symbols defined in different sections. That is the + * expression "symbol1 - symbol2 + constant" is a relocatable expression when + * both symbols are defined in some section. For this type of relocation the + * both relocations entries are scattered relocation entries. The value of + * symbol1 is stored in the first relocation entry's r_value field and the + * value of symbol2 is stored in the pair's r_value field. + * + * A special case for a prebound lazy pointer is needed to beable to set the + * value of the lazy pointer back to its non-prebound state. This is done + * using the GENERIC_RELOC_PB_LA_PTR r_type. This is a scattered relocation + * entry where the r_value feild is the value of the lazy pointer not prebound. + */ +enum reloc_type_generic +{ + GENERIC_RELOC_VANILLA, /* generic relocation as discribed above */ + GENERIC_RELOC_PAIR, /* Only follows a GENERIC_RELOC_SECTDIFF */ + GENERIC_RELOC_SECTDIFF, + GENERIC_RELOC_PB_LA_PTR, /* prebound lazy pointer */ + GENERIC_RELOC_LOCAL_SECTDIFF +}; + +#endif /* _MACHO_RELOC_H_ */ diff --git a/data/mach-o/headers/stab.h b/data/mach-o/headers/stab.h new file mode 100644 index 0000000..e9e15b2 --- /dev/null +++ b/data/mach-o/headers/stab.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 1999 Apple Computer, Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ +#ifndef _MACHO_STAB_H_ +#define _MACHO_STAB_H_ +/* $NetBSD: stab.h,v 1.4 1994/10/26 00:56:25 cgd Exp $ */ + +/*- + * Copyright (c) 1991 The Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)stab.h 5.2 (Berkeley) 4/4/91 + */ + +/* + * This file gives definitions supplementing for permanent symbol + * table entries of Mach-O files. Modified from the BSD definitions. The + * modifications from the original definitions were changing what the values of + * what was the n_other field (an unused field) which is now the n_sect field. + * These modifications are required to support symbols in an arbitrary number of + * sections not just the three sections (text, data and bss) in a BSD file. + * The values of the defined constants have NOT been changed. + * + * These must have one of the N_STAB bits on. The n_value fields are subject + * to relocation according to the value of their n_sect field. So for types + * that refer to things in sections the n_sect field must be filled in with the + * proper section ordinal. For types that are not to have their n_value field + * relocatated the n_sect field must be NO_SECT. + */ + +/* + * Symbolic debugger symbols. The comments give the conventional use for + * + * .stabs "n_name", n_type, n_sect, n_desc, n_value + * + * where n_type is the defined constant and not listed in the comment. Other + * fields not listed are zero. n_sect is the section ordinal the entry is + * refering to. + */ +#define N_GSYM 0x20 /* global symbol: name,,NO_SECT,type,0 */ +#define N_FNAME 0x22 /* procedure name (f77 kludge): name,,NO_SECT,0,0 */ +#define N_FUN 0x24 /* procedure: name,,n_sect,linenumber,address */ +#define N_STSYM 0x26 /* static symbol: name,,n_sect,type,address */ +#define N_LCSYM 0x28 /* .lcomm symbol: name,,n_sect,type,address */ +#define N_BNSYM 0x2e /* begin nsect sym: 0,,n_sect,0,address */ +#define N_OPT 0x3c /* emitted with gcc2_compiled and in gcc source */ +#define N_RSYM 0x40 /* register sym: name,,NO_SECT,type,register */ +#define N_SLINE 0x44 /* src line: 0,,n_sect,linenumber,address */ +#define N_ENSYM 0x4e /* end nsect sym: 0,,n_sect,0,address */ +#define N_SSYM 0x60 /* structure elt: name,,NO_SECT,type,struct_offset */ +#define N_SO 0x64 /* source file name: name,,n_sect,0,address */ +#define N_OSO 0x66 /* object file name: name,,0,0,st_mtime */ +#define N_LSYM 0x80 /* local sym: name,,NO_SECT,type,offset */ +#define N_BINCL 0x82 /* include file beginning: name,,NO_SECT,0,sum */ +#define N_SOL 0x84 /* #included file name: name,,n_sect,0,address */ +#define N_PARAMS 0x86 /* compiler parameters: name,,NO_SECT,0,0 */ +#define N_VERSION 0x88 /* compiler version: name,,NO_SECT,0,0 */ +#define N_OLEVEL 0x8A /* compiler -O level: name,,NO_SECT,0,0 */ +#define N_PSYM 0xa0 /* parameter: name,,NO_SECT,type,offset */ +#define N_EINCL 0xa2 /* include file end: name,,NO_SECT,0,0 */ +#define N_ENTRY 0xa4 /* alternate entry: name,,n_sect,linenumber,address */ +#define N_LBRAC 0xc0 /* left bracket: 0,,NO_SECT,nesting level,address */ +#define N_EXCL 0xc2 /* deleted include file: name,,NO_SECT,0,sum */ +#define N_RBRAC 0xe0 /* right bracket: 0,,NO_SECT,nesting level,address */ +#define N_BCOMM 0xe2 /* begin common: name,,NO_SECT,0,0 */ +#define N_ECOMM 0xe4 /* end common: name,,n_sect,0,0 */ +#define N_ECOML 0xe8 /* end common (local name): 0,,n_sect,0,address */ +#define N_LENG 0xfe /* second stab entry with length information */ + +/* + * for the berkeley pascal compiler, pc(1): + */ +#define N_PC 0x30 /* global pascal symbol: name,,NO_SECT,subtype,line */ + +#endif /* _MACHO_STAB_H_ */ diff --git a/data/mach-o/inject.c b/data/mach-o/inject.c new file mode 100644 index 0000000..57214d2 --- /dev/null +++ b/data/mach-o/inject.c @@ -0,0 +1,756 @@ +#include "inject.h" +#include "read_dyld_info.h" +#include "headers/loader.h" +#include "headers/nlist.h" +#include "headers/reloc.h" +#include + +addr_t b_allocate_vmaddr(const struct binary *binary) { + addr_t max = 0; + + for(uint32_t i = 0; i < binary->nsegments; i++) { + const range_t *range = &binary->segments[i].vm_range; + addr_t newmax = range->start + range->size; + if(newmax > max) max = newmax; + } + + return (max + 0xfff) & ~0xfffu; +} + +// this function is used by both b_macho_extend_cmds and b_inject_macho_binary +static void handle_retarded_dyld_info(void *ptr, uint32_t size, int num_segments, bool kill_dylibs, bool kill_dones) { + // seriously, take a look at dyldinfo.cpp from ld64, especially, in this case, the separate handing of different LC_DYLD_INFO sections and the different meaning of BIND_OPCODE_DONE in lazy bind vs the other binds + // not to mention the impossibility of reading this data without knowing every single opcode + // and the lack of nop + uint8_t flat_lookup = BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | (((uint8_t) BIND_SPECIAL_DYLIB_FLAT_LOOKUP) & ~BIND_OPCODE_MASK); + void *end = ptr + size; + while(ptr != end) { + uint8_t byte = read_int(&ptr, end, uint8_t); + uint8_t immediate = byte & BIND_IMMEDIATE_MASK; + uint8_t opcode = byte & BIND_OPCODE_MASK; + switch(opcode){ + // things we actually care about: + case BIND_OPCODE_DONE: + if(kill_dones) { + *((uint8_t *) ptr - 1) = BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER; + } + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: { + // update the segment number + uint8_t *p = ptr - 1; + //printf("incr'ing %u by %u\n", (unsigned int) immediate, (unsigned int) num_segments); + *p = (*p & BIND_OPCODE_MASK) | (immediate + num_segments); + read_uleb128(&ptr, end); + break; + } + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + if(kill_dylibs) { + *((uint8_t *) ptr - 1) = flat_lookup; + } + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: { + void *start = ptr - 1; + read_uleb128(&ptr, end); + if(kill_dylibs) { + memset(start, flat_lookup, ptr - start); + } + break; + } + // things we have to get through + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + ptr += strnlen(ptr, end - ptr); + if(ptr == end) + break; + case BIND_OPCODE_SET_ADDEND_SLEB: // actually sleb (and I like how read_uleb128 and read_sleb128 in dyldinfo.cpp are completely separate functions), but read_uleb128 should work + case BIND_OPCODE_ADD_ADDR_ULEB: + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + read_uleb128(&ptr, end); + break; + + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + read_uleb128(&ptr, end); + read_uleb128(&ptr, end); + break; + } + } +} + + +uint32_t b_macho_extend_cmds(struct binary *binary, size_t space) { + size_t old_size = b_mach_hdr(binary)->sizeofcmds; + size_t new_size = old_size + space; + if((new_size >> 12) == (old_size >> 12)) { + // good enough, it'll fit + return (new_size + 0xfff) & ~0xfff; + } + + // looks like we need to make a duplicate header and do ugly stuff + size_t stuff_size = (sizeof(struct mach_header) + sizeof(struct segment_command) + sizeof(struct section) + new_size + 0xfff) & ~0xfff; + + #define X(a) if(a) a += stuff_size; + CMD_ITERATE(b_mach_hdr(binary), cmd) { + switch(cmd->cmd) { + case LC_SEGMENT: { + struct segment_command *seg = (void *) cmd; + seg->fileoff += stuff_size; + struct section *sect = (void *) (seg + 1); + for(uint32_t i = 0; i < seg->nsects; i++, sect++) { + sect->offset += stuff_size; + X(sect->reloff) + } + break; + } + case LC_SYMTAB: { + struct symtab_command *sym = (void *) cmd; + X(sym->symoff) + X(sym->stroff) + break; + } + case LC_DYSYMTAB: { + struct dysymtab_command *dys = (void *) cmd; + X(dys->tocoff) + X(dys->modtaboff) + X(dys->extrefsymoff) + X(dys->indirectsymoff) + X(dys->extreloff) + X(dys->locreloff) + break; + } + case LC_TWOLEVEL_HINTS: { + struct twolevel_hints_command *two = (void *) cmd; + X(two->offset) + break; + } + case LC_CODE_SIGNATURE: + case LC_SEGMENT_SPLIT_INFO: + case 38 /*LC_FUNCTION_STARTS*/: { + // this is sort of a best (but rather bad) guess - all three commands will probably be screwed up by being moved like this + struct linkedit_data_command *dat = (void *) cmd; + X(dat->dataoff) + break; + } + case LC_ENCRYPTION_INFO: { + struct encryption_info_command *enc = (void *) cmd; + X(enc->cryptoff) + break; + } + case LC_DYLD_INFO: + case LC_DYLD_INFO_ONLY: { + struct dyld_info_command *dyl = (void *) cmd; + X(dyl->rebase_off) + X(dyl->export_off) + #define Y(a) if(dyl->a##_off) { \ + prange_t pr = rangeconv_off((range_t) {binary, dyl->a##_off, dyl->a##_size}, MUST_FIND); \ + handle_retarded_dyld_info(pr.start, pr.size, 1, false, false); \ + dyl->a##_off += stuff_size; \ + } + Y(bind) + Y(weak_bind) + Y(lazy_bind) + #undef Y + break; + } + } + } + #undef X + + binary->valid_range = pdup(binary->valid_range, ((binary->valid_range.size + 0xfff) & ~0xfff) + stuff_size, stuff_size); + struct mach_header *hdr = binary->valid_range.start; + struct segment_command *seg = (void *) (hdr + 1); + struct section *sect = (void *) (seg + 1); + memcpy(hdr, binary->valid_range.start + stuff_size, sizeof(*hdr)); + memcpy(sect + 1, binary->valid_range.start + stuff_size + sizeof(struct mach_header), hdr->sizeofcmds); + + hdr->ncmds++; + hdr->sizeofcmds += sizeof(*seg) + sizeof(*sect); + + seg->cmd = LC_SEGMENT; + seg->cmdsize = sizeof(*seg) + sizeof(*sect); + // yes, it MUST be called __TEXT. + static const char segname[16] = "__TEXT"; + memcpy(seg->segname, segname, 16); + seg->vmaddr = b_allocate_vmaddr(binary); + seg->vmsize = stuff_size; + seg->fileoff = 0; + seg->filesize = stuff_size; + seg->maxprot = seg->initprot = PROT_READ | PROT_EXEC; + seg->nsects = 1; + seg->flags = 0; + + // we need a section to make codesign_allocate happy + static const char sectname[16] = "__useless"; + memcpy(sect->sectname, sectname, 16); + memcpy(sect->segname, segname, 16); + sect->addr = seg->vmaddr + stuff_size; + sect->size = 0; + sect->offset = stuff_size; + sect->align = 0; + sect->reloff = 0; + sect->nreloc = 0; + sect->flags = 0; + sect->reserved1 = 0; + sect->reserved2 = 0; + + return stuff_size - sizeof(struct mach_header); +} + + +// cctool's checkout.c insists on this exact order +enum { + MM_BIND, MM_WEAK_BIND, MM_LAZY_BIND, + MM_LOCREL, + MM_SYMTAB, + MM_LOCALSYM, MM_EXTDEFSYM, MM_UNDEFSYM, + MM_EXTREL, + MM_INDIRECT, + MM_STRTAB, + NMOVEME +}; + +struct linkedit_info { + arange_t linkedit_range; + void *linkedit_ptr; + + // things we need to move: + // 0. string table + // 1-3. {local, extdef, undef}sym + // 4-5. {locrel, extrel} + // 6. indirect syms + // 7-9. dyld info {, weak_, lazy_}bind + // [hey, I will just assume that nobody has any section relocations because it makes things simpler!] + // things we need to update: + // - symbols reference string table + // - relocations reference symbols + // - indirect syms reference symbols + // - (section data references indirect syms) + struct moveme { + uint32_t *off, *size; + uint32_t element_size; + + int off_base; + + void *copied_to; + void *copied_from; + uint32_t copied_size; + } moveme[NMOVEME]; + + struct symtab_command *symtab; + struct dysymtab_command *dysymtab; + struct dyld_info_command *dyld_info; +}; + +static const struct moveref { + int target; + ptrdiff_t offset; +} moveref[NMOVEME] = { + [MM_LOCALSYM] = {MM_STRTAB, offsetof(struct nlist, n_un.n_strx)}, + [MM_EXTDEFSYM] = {MM_STRTAB, offsetof(struct nlist, n_un.n_strx)}, + [MM_UNDEFSYM] = {MM_STRTAB, offsetof(struct nlist, n_un.n_strx)}, + + // hooray for little endian + [MM_LOCREL] = {MM_UNDEFSYM, 4}, + [MM_EXTREL] = {MM_UNDEFSYM, 4}, + // the whole thing is a symbol number + [MM_INDIRECT] = {MM_UNDEFSYM, 0} +}; + +static bool catch_linkedit(struct mach_header *hdr, struct linkedit_info *li, bool patch) { + memset(li, 0, sizeof(*li)); + bool ret = false; + CMD_ITERATE(hdr, cmd) { + restart: + switch(cmd->cmd) { + case LC_SEGMENT: { + struct segment_command *seg = (void *) cmd; + if(!strcmp(seg->segname, "__LINKEDIT")) { + li->linkedit_range.start = seg->fileoff; + li->linkedit_range.size = seg->filesize; + ret = true; + goto patchout; + break; + } + + break; + } + case LC_SYMTAB: { + struct symtab_command *symtab = (void *) cmd; + li->symtab = symtab; + + li->moveme[MM_STRTAB].off = &symtab->stroff; + li->moveme[MM_STRTAB].size = &symtab->strsize; + li->moveme[MM_STRTAB].element_size = 1; + + li->moveme[MM_SYMTAB].off = &symtab->symoff; + li->moveme[MM_SYMTAB].size = &symtab->nsyms; + li->moveme[MM_SYMTAB].element_size = sizeof(struct nlist); + li->moveme[MM_SYMTAB].off_base = -1; + + break; + } + case LC_DYSYMTAB: { + struct dysymtab_command *dys = (void *) cmd; + li->dysymtab = dys; + + li->moveme[MM_LOCALSYM].off = &dys->ilocalsym; + li->moveme[MM_LOCALSYM].size = &dys->nlocalsym; + li->moveme[MM_LOCALSYM].element_size = sizeof(struct nlist); + li->moveme[MM_LOCALSYM].off_base = MM_SYMTAB; + + li->moveme[MM_EXTDEFSYM].off = &dys->iextdefsym; + li->moveme[MM_EXTDEFSYM].size = &dys->nextdefsym; + li->moveme[MM_EXTDEFSYM].element_size = sizeof(struct nlist); + li->moveme[MM_EXTDEFSYM].off_base = MM_SYMTAB; + + li->moveme[MM_UNDEFSYM].off = &dys->iundefsym; + li->moveme[MM_UNDEFSYM].size = &dys->nundefsym; + li->moveme[MM_UNDEFSYM].element_size = sizeof(struct nlist); + li->moveme[MM_UNDEFSYM].off_base = MM_SYMTAB; + + li->moveme[MM_LOCREL].off = &dys->locreloff; + li->moveme[MM_LOCREL].size = &dys->nlocrel; + li->moveme[MM_LOCREL].element_size = sizeof(struct relocation_info); + + li->moveme[MM_EXTREL].off = &dys->extreloff; + li->moveme[MM_EXTREL].size = &dys->nextrel; + li->moveme[MM_EXTREL].element_size = sizeof(struct relocation_info); + + li->moveme[MM_INDIRECT].off = &dys->indirectsymoff; + li->moveme[MM_INDIRECT].size = &dys->nindirectsyms; + li->moveme[MM_INDIRECT].element_size = 4; + + break; + } + case LC_DYLD_INFO_ONLY: + case LC_DYLD_INFO: { + struct dyld_info_command *di = (void *) cmd; + li->dyld_info = di; + + if(patch) { + di->rebase_off = 0; + di->rebase_size = 0; + di->export_off = 0; + di->export_size = 0; + } + + li->moveme[MM_BIND].off = &di->bind_off; + li->moveme[MM_BIND].size = &di->bind_size; + li->moveme[MM_BIND].element_size = 1; + + li->moveme[MM_WEAK_BIND].off = &di->weak_bind_off; + li->moveme[MM_WEAK_BIND].size = &di->weak_bind_size; + li->moveme[MM_WEAK_BIND].element_size = 1; + + li->moveme[MM_LAZY_BIND].off = &di->lazy_bind_off; + li->moveme[MM_LAZY_BIND].size = &di->lazy_bind_size; + li->moveme[MM_LAZY_BIND].element_size = 1; + break; + } + patchout: + case LC_CODE_SIGNATURE: + case LC_SEGMENT_SPLIT_INFO: + case 38 /*LC_FUNCTION_STARTS*/: + // hope you didn't need that stuff <3 + if(patch) { + hdr->sizeofcmds -= cmd->cmdsize; + size_t copysize = hdr->sizeofcmds - ((char *) cmd - (char *) (hdr + 1)); + hdr->ncmds--; + memcpy(cmd, (char *) cmd + cmd->cmdsize, copysize); + // update this thing from the CMD_ITERATE macro + end = (void *) (hdr + 1) + hdr->sizeofcmds; + // don't run off the end + if(!copysize) goto end; + goto restart; + } + break; + } + } + end: + // we want both binaries to have a symtab and dysymtab, makes things easier + if(!li->symtab || !li->dysymtab) die("symtab/dysymtab missing"); + return ret; +} + +static void fixup_stub_helpers(int cputype, void *base, size_t size, uint32_t incr) { + if(!size) return; + size_t skip_begin, skip_end, offset, stride; + switch(cputype) { + case CPU_TYPE_ARM: + skip_begin = 0x24; + skip_end = 0; + offset = 8; + stride = 0xc; + break; + case CPU_TYPE_X86: + skip_begin = 0; + skip_end = 0xa; + offset = 1; + stride = 0xa; + break; + default: + die("stub_helpers, but unknown cpu type"); + } + if(size < (skip_begin + skip_end)) { + die("unknown stub_helpers format (too small)"); + } + base += skip_begin; size -= skip_begin; + while(size >= skip_end + stride) { + *((uint32_t *) (base + offset)) += incr; + base += stride; size -= stride; + } +} + +void b_inject_macho_binary(struct binary *target, const struct binary *binary, addr_t (*find_hack_func)(const struct binary *binary), bool userland) { +#define ADD_COMMAND(size) ({ \ + void *ret = (char *) hdr + sizeof(struct mach_header) + hdr->sizeofcmds; \ + uint32_t newsize = hdr->sizeofcmds + size; \ + if(newsize > sizeofcmds_limit) { \ + die("not enough space for commands"); \ + } \ + hdr->ncmds++; \ + hdr->sizeofcmds += (uint32_t) (size); \ + ret; \ + }) + +#define ADD_SEGMENT(size) ({ \ + uint32_t ret = (seg_off + 0xfff) & ~0xfff; \ + seg_off = ret + (size); \ + ret; \ + }) + +#define ADD_SEGMENT_ADDR(size) ({ \ + uint32_t ret = (seg_addr + 0xfff) & ~0xfff; \ + seg_addr = ret + (size); \ + ret; \ + }) + + // the 0x100 is arbitrary, but intended to please codesign_allocate + uint32_t sizeofcmds_limit = b_macho_extend_cmds(target, b_mach_hdr(binary)->sizeofcmds + 0x100); + + size_t seg_off = target->valid_range.size; + addr_t seg_addr = 0; + + struct mach_header *hdr = b_mach_hdr(target); + hdr->flags &= ~MH_PIE; + + const struct binary *binaries[] = {binary, target}; + + // in userland mode, we cut off the LINKEDIT segment (for target, only if it's at the end of the binary) + struct linkedit_info li[2]; + if(userland) { + for(int i = 0; i < 2; i++) { + if(catch_linkedit(b_mach_hdr(binaries[i]), &li[i], i == 1)) { + li[i].linkedit_ptr = rangeconv_off((range_t) {binaries[i], li[i].linkedit_range.start, li[i].linkedit_range.size}, MUST_FIND).start; + } + } + if((size_t) (li[1].linkedit_range.start + li[1].linkedit_range.size) == seg_off) { + target->valid_range.size = seg_off = li[1].linkedit_range.start; + } + if((li[0].dyld_info != 0) != (li[1].dyld_info != 0)) { + die("LC_DYLD_INFO(_ONLY) should be in both or neither"); + } + } + + uint32_t init_ptrs[100]; + unsigned num_init_ptrs = 0; + uint32_t *reserved1s[100]; + unsigned num_reserved1s = 0; + struct copy { ptrdiff_t off; void *start; size_t size; } copies[100]; + unsigned num_copies = 0; + + unsigned num_segments = 0; + if(userland) { + CMD_ITERATE(hdr, cmd) { + if(cmd->cmd == LC_SEGMENT) { + num_segments++; + struct segment_command *seg = (void *) cmd; + struct section *sections = (void *) (seg + 1); + for(uint32_t i = 0; i < seg->nsects; i++) { + struct section *sect = §ions[i]; + switch(sect->flags & SECTION_TYPE) { + case S_NON_LAZY_SYMBOL_POINTERS: + case S_LAZY_SYMBOL_POINTERS: + case S_SYMBOL_STUBS: + if(num_reserved1s < 100) reserved1s[num_reserved1s++] = §->reserved1; + break; + } + + if(li[0].dyld_info && !strcmp(sect->sectname, "__stub_helper")) { + void *segdata = rangeconv_off((range_t) {target, seg->fileoff, seg->filesize}, MUST_FIND).start; + fixup_stub_helpers(hdr->cputype, segdata + sect->offset - seg->fileoff, sect->size, *li[0].moveme[MM_LAZY_BIND].size); + } + } + } + } + } + + CMD_ITERATE(b_mach_hdr(binary), cmd) { + switch(cmd->cmd) { + case LC_SEGMENT: { + struct segment_command *seg = (void *) cmd; + + if(userland && !strcmp(seg->segname, "__LINKEDIT")) continue; + + size_t size = sizeof(struct segment_command) + seg->nsects * sizeof(struct section); + + // make seg_addr useful + addr_t new_addr = seg->vmaddr + seg->vmsize; + if(new_addr > seg_addr) seg_addr = new_addr; + + struct segment_command *newseg = ADD_COMMAND(size); + memcpy(newseg, seg, size); + prange_t pr = rangeconv_off((range_t) {binary, seg->fileoff, seg->filesize}, MUST_FIND); + + newseg->fileoff = (uint32_t) ADD_SEGMENT(pr.size); + //printf("setting fileoff to %u\n", newseg->fileoff); + if(num_copies < 100) copies[num_copies++] = (struct copy) {newseg->fileoff, pr.start, pr.size}; + + struct section *sections = (void *) (newseg + 1); + for(uint32_t i = 0; i < seg->nsects; i++) { + struct section *sect = §ions[i]; + sect->offset = newseg->fileoff + sect->addr - newseg->vmaddr; + // ZEROFILL is okay because iBoot always zeroes vmsize - filesize + if(!userland && (sect->flags & SECTION_TYPE) == S_MOD_INIT_FUNC_POINTERS) { + uint32_t *p = rangeconv_off((range_t) {binary, sect->offset, sect->size}, MUST_FIND).start; + size_t num = sect->size / 4; + while(num--) { + if(num_init_ptrs < 100) init_ptrs[num_init_ptrs++] = *p++; + } + } + } + break; + } + case LC_LOAD_DYLIB: + if(userland) { + void *newcmd = ADD_COMMAND(cmd->cmdsize); + memcpy(newcmd, cmd, cmd->cmdsize); + } + break; + } + } + + + // now deal with the init pointers (if not userland) + // this code is really gross + if(num_init_ptrs > 0) { + if(num_init_ptrs == 1) { // hey, correct plurals are nice + fprintf(stderr, "note: 1 constructor function is present; using the hack_func\n"); + } else { + fprintf(stderr, "note: %d constructor functions are present; using the hack_func\n", num_init_ptrs); + } + + if(!find_hack_func) { + die("...but there was no find_hack_func"); + } + + // ldr pc, [pc] + uint16_t part0[] = {0xf8df, 0xf000}; + + // push {r0-r3, lr}; adr lr, f+1; ldr pc, a; f: b next; a: .long 0; next: + // (the address of the init func) + // + uint16_t part1[] = {0xb50f, 0xf20f, 0x0e07, 0xf8df, 0xf004, 0xe001}; + // (bytes_to_move bytes of stuff) + // pop {r0-r3, lr} + static const uint16_t part2[] = {0xe8bd, 0x400f}; + // ldr pc, [pc] + static const uint16_t part3[] = {0xf8df, 0xf000}; + + uint32_t bytes_to_move = 12; // don't cut the MRC in two! + + addr_t hack_func = find_hack_func(target); + fprintf(stderr, "hack_func = %08llx\n", (long long) hack_func); + prange_t hack_func_pr = rangeconv((range_t) {target, hack_func & ~1, bytes_to_move}, MUST_FIND); + + // allocate a new segment for the stub + + uint32_t stub_size = (uint32_t) ((sizeof(part1) + 4) * num_init_ptrs + sizeof(part2) + bytes_to_move + sizeof(part3) + 4); + + if(!(hack_func & 1)) { + die("hack func 0x%llx is not thumb", (uint64_t) hack_func); + } + + struct segment_command *newseg = ADD_COMMAND(sizeof(struct segment_command)); + + newseg->cmd = LC_SEGMENT; + newseg->cmdsize = sizeof(struct segment_command); + memset(newseg->segname, 0, 16); + strcpy(newseg->segname, "__CRAP"); + newseg->vmaddr = ADD_SEGMENT_ADDR(stub_size); + newseg->vmsize = stub_size; + newseg->fileoff = ADD_SEGMENT(stub_size); + newseg->filesize = stub_size; + newseg->maxprot = newseg->initprot = PROT_READ | PROT_EXEC; + newseg->nsects = 0; + newseg->flags = 0; + + void *ptr = malloc(stub_size); + for(unsigned i = 0; i < num_init_ptrs; i++) { + memcpy(ptr, part1, sizeof(part1)); + ptr += sizeof(part1); + memcpy(ptr, &init_ptrs[i], 4); + ptr += 4; + part1[0] = 0x46c0; + } + + memcpy(ptr, part2, sizeof(part2)); + ptr += sizeof(part2); + + memcpy(ptr, hack_func_pr.start, bytes_to_move); + ptr += bytes_to_move; + + memcpy(ptr, part3, sizeof(part3)); + ptr += sizeof(part3); + + uint32_t new_addr = hack_func + bytes_to_move; + memcpy(ptr, &new_addr, 4); + ptr += 4; + + new_addr = newseg->vmaddr | 1; + memcpy(hack_func_pr.start, part0, sizeof(part0)); + memcpy(hack_func_pr.start + sizeof(part0), &new_addr, 4); + + if(num_copies < 100) copies[num_copies++] = (struct copy) {newseg->fileoff, ptr, stub_size}; + } + + autofree char *linkedit = NULL; + + if(userland) { + // build the new LINKEDIT + uint32_t newsize = 0; + for(int i = 0; i < NMOVEME; i++) { + for(int l = 0; l < 2; l++) { + struct moveme *m = &li[l].moveme[i]; + if(!m->size) { + static uint32_t zero = 0; + m->size = m->off = &zero; + m->element_size = 1; + } + if(m->off_base != -1) { + newsize += *m->size * m->element_size; + } + } + } + + if(newsize != 0) { + uint32_t linkedit_off = ADD_SEGMENT(newsize); + linkedit = malloc(newsize); + uint32_t off = 0; + + for(int i = 0; i < NMOVEME; i++) { + uint32_t s = 0; + for(int l = 0; l < 2; l++) { + struct moveme *m = &li[l].moveme[i]; + m->copied_size = *m->size * m->element_size; + m->copied_to = linkedit + off + s; + if(m->off_base > 0) { + // the value is an index into a table represented by another moveme (i.e. the symtab) + m->copied_from = li[l].moveme[m->off_base].copied_from + *m->off * m->element_size; + } else { + // the value is a file offset + // if 0, just plain copy; if -1, the references will handle copying + m->copied_from = li[l].linkedit_ptr - li[l].linkedit_range.start + *m->off; + } + if(m->off_base != -1) { + memcpy(m->copied_to, m->copied_from, m->copied_size); + } + s += m->copied_size; + } + //printf("i=%d s=%u off=%u\n", i, s, off); + // update the one to load + struct moveme *m = &li[1].moveme[i]; + *m->off = linkedit_off + off; + if(m->off_base > 0) { + *m->off = (*m->off - *li[1].moveme[m->off_base].off) / m->element_size; + } + *m->size = s / m->element_size; + + if(m->off_base != -1) { + off += s; + } + } + + // update struct references (which are out of order, yay) + off = 0; + for(int i = 0; i < 2; i++) { + for(int j = MM_LOCREL; j <= MM_INDIRECT; j++) { + int k = moveref[j].target; + if(!k) continue; + + struct moveme *m = &li[i].moveme[j]; + for(void *ptr = m->copied_to; ptr < m->copied_to + m->copied_size; ptr += m->element_size) { + uint32_t diff = 0; + int b = li[i].moveme[k].off_base; + if(b > 0) { + // A1 A2 B1 B2 C1 C2 + // 0: <---------> + // 1: <------------> + int orig_off = (li[i].moveme[k].copied_from - li[i].moveme[b].copied_from) / li[i].moveme[k].element_size; + int new_off = (li[i].moveme[k].copied_to - li[0].moveme[b].copied_to) / li[i].moveme[k].element_size; + diff = new_off - orig_off; + } else { + // A B + // 0: + // 1: <-> + if(i == 1) { + diff = li[0].moveme[k].copied_size / li[0].moveme[k].element_size; + } + } + + uint32_t *p = ptr + moveref[j].offset; + if(*p < 0x10000000) *p += diff; + } + } + } + + // update library numbers in symbol table + { + struct moveme *restrict m = &li[0].moveme[MM_UNDEFSYM]; + for(struct nlist *nl = m->copied_to; (void *) (nl + 1) <= (m->copied_to + m->copied_size); nl++) { + unsigned lib = GET_LIBRARY_ORDINAL(nl->n_desc); + if(lib != SELF_LIBRARY_ORDINAL && lib <= MAX_LIBRARY_ORDINAL) { + + SET_LIBRARY_ORDINAL(nl->n_desc, DYNAMIC_LOOKUP_ORDINAL); + } + } + } + + // ... and update section references + for(unsigned i = 0; i < num_reserved1s; i++) { + *reserved1s[i] += *li[0].moveme[MM_INDIRECT].size; + } + + // ... and dyld info + if(li->dyld_info) { + for(int i = MM_BIND; i <= MM_LAZY_BIND; i++) { + if(*li[1].moveme[i].off) { + handle_retarded_dyld_info(linkedit - linkedit_off + *li[1].moveme[i].off, *li[0].moveme[i].size, num_segments, true, i != MM_LAZY_BIND); + } + } + } + + struct segment_command *newseg = ADD_COMMAND(sizeof(struct segment_command)); + newseg->cmd = LC_SEGMENT; + newseg->cmdsize = sizeof(struct segment_command); + memset(newseg->segname, 0, 16); + strcpy(newseg->segname, "__LINKEDIT"); + newseg->vmaddr = ADD_SEGMENT_ADDR(newsize); + newseg->vmsize = (newsize + 0xfff) & ~0xfff; + newseg->fileoff = linkedit_off; + newseg->filesize = newsize; + newseg->maxprot = newseg->initprot = PROT_READ | PROT_WRITE; + newseg->nsects = 0; + newseg->flags = 0; + + //printf("off=%d newsize=%d\n", linkedit_off, newsize); + if(num_copies < 100) copies[num_copies++] = (struct copy) {linkedit_off, linkedit, newsize}; + } + + } + + // finally, expand the binary in memory and actually copy in the new stuff + target->valid_range = pdup(target->valid_range, seg_off, 0); + for(unsigned i = 0; i < num_copies; i++) { + memcpy(target->valid_range.start + copies[i].off, copies[i].start, copies[i].size); + } +} + diff --git a/data/mach-o/inject.h b/data/mach-o/inject.h new file mode 100644 index 0000000..f6ffaee --- /dev/null +++ b/data/mach-o/inject.h @@ -0,0 +1,10 @@ +#pragma once +#include "binary.h" + +addr_t b_allocate_vmaddr(const struct binary *binary); + +// these two functions will modify binary->valid_range and trash everything else. +uint32_t b_macho_extend_cmds(struct binary *binary, size_t space); +// this function works for both the kernel and uselrand binaries. for userland, pass NULL for find_hack_func. +void b_inject_macho_binary(struct binary *target, const struct binary *inject, addr_t (*find_hack_func)(const struct binary *binary), bool userland); + diff --git a/data/mach-o/link.c b/data/mach-o/link.c new file mode 100644 index 0000000..9d5ad86 --- /dev/null +++ b/data/mach-o/link.c @@ -0,0 +1,466 @@ +#include "link.h" +#include "headers/loader.h" +#include "headers/nlist.h" +#include "headers/reloc.h" +#include "headers/arm_reloc.h" +#include +#include "read_dyld_info.h" + +static addr_t lookup_symbol_or_do_stuff(lookupsym_t lookup_sym, void *context, const char *name, bool weak, bool userland) { + addr_t sym = lookup_sym(context, name); + if(!sym) { + if(userland) { + // let it pass + } else if(!strcmp(name, "dyld_stub_binder")) { + sym = 0xdeadbeef; + } else if(weak) { + fprintf(stderr, "lookup_nth_symbol: warning: couldn't find weak symbol %s\n", name); + } else { + die("couldn't find symbol %s\n", name); + } + } + return sym; +} + +static addr_t lookup_nth_symbol(const struct binary *load, uint32_t symbolnum, lookupsym_t lookup_sym, void *context, bool userland) { + struct nlist *nl = b_macho_nth_symbol(load, symbolnum); + bool weak = nl->n_desc & N_WEAK_REF; + const char *name = load->mach->strtab + nl->n_un.n_strx; + return lookup_symbol_or_do_stuff(lookup_sym, context, name, weak, userland); +} + +static void relocate_area(struct binary *load, uint32_t reloff, uint32_t nreloc, enum reloc_mode mode, lookupsym_t lookup_sym, void *context, addr_t slide) { + struct relocation_info *things = rangeconv_off((range_t) {load, reloff, nreloc * sizeof(struct relocation_info)}, MUST_FIND).start; + for(uint32_t i = 0; i < nreloc; i++) { + if(things[i].r_length != 2) { + die("bad relocation length"); + } + addr_t address = things[i].r_address; + if(address == 0 || things[i].r_symbolnum == R_ABS) continue; + address += b_macho_reloc_base(load); + uint32_t *p = rangeconv((range_t) {load, address, 4}, MUST_FIND).start; + + addr_t value; + if(things[i].r_extern) { + if(mode == RELOC_LOCAL_ONLY) continue; + value = lookup_nth_symbol(load, things[i].r_symbolnum, lookup_sym, context, mode == RELOC_USERLAND); + if(value == 0 && mode == RELOC_USERLAND) continue; + } else { + if(mode == RELOC_EXTERN_ONLY || mode == RELOC_USERLAND) continue; + // *shrug* + value = slide; + } + + things[i].r_address = 0; + things[i].r_symbolnum = R_ABS; + + if(mode == RELOC_EXTERN_ONLY && things[i].r_type != ARM_RELOC_VANILLA) { + die("non-VANILLA relocation but we are relocating without knowing the slide; use __attribute__((long_call)) to get rid of these"); + } + switch(things[i].r_type) { + case ARM_RELOC_VANILLA: + //printf("%x, %x += %x\n", address, *p, value); + if(rangeconv((range_t) {load, *p, 0}, 0).start) { + // when dyld_stub_binding_helper (which would just crash, btw) is present, entries in the indirect section point to it; usually this increments to point to the right dyld_stub_binding_helper, then that's clobbered by the indirect code. when we do prelinking, the indirect code runs first and we would be relocating the already-correctly-located importee symbol, so we add this check (easier than actually checking that it's not in the indirect section) to make sure we're not relocating nonsense. + *p += value; + } + //else printf("skipping %x\n", *p); + break; + case ARM_RELOC_BR24: { + if(!things[i].r_pcrel) die("weird relocation"); + uint32_t ins = *p; + uint32_t off = ins & 0x00ffffff; + if(ins & 0x00800000) off |= 0xff000000; + off <<= 2; + off += (value - slide); + if((off & 0xfc000000) != 0 && + (off & 0xfc000000) != 0xfc000000) { + die("BR24 relocation out of range"); + } + uint32_t cond = ins >> 28; + if(value & 1) { + if(cond != 0xe && cond != 0xf) die("can't convert BL with condition to BLX (which must be unconditional)"); + ins = (ins & 0x0effffff) | 0xf0000000 | ((off & 2) << 24); + } else if(cond == 0xf) { + ins = (ins & 0x0fffffff) | 0xe0000000; + } + + ins = (ins & 0xff000000) | ((off >> 2) & 0x00ffffff); + *p = ins; + break; + } + default: + die("unknown relocation type %d", things[i].r_type); + } + + } +} + +static void go_indirect(struct binary *load, uint32_t offset, uint32_t size, uint32_t flags, uint32_t reserved1, uint32_t reserved2, enum reloc_mode mode, lookupsym_t lookup_sym, void *context, addr_t slide) { + uint8_t type = flags & SECTION_TYPE; + uint8_t pointer_size = b_pointer_size(load); + switch(type) { + case S_NON_LAZY_SYMBOL_POINTERS: + case S_LAZY_SYMBOL_POINTERS: { + uint32_t indirect_table_offset = reserved1; + const struct dysymtab_command *dysymtab = load->mach->dysymtab; + + + uint32_t stride = type == S_SYMBOL_STUBS ? reserved2 : pointer_size; + uint32_t num_syms = size / stride; + + if(stride < pointer_size || + num_syms * stride != size || + dysymtab->nindirectsyms > ((addr_t) -(dysymtab->indirectsymoff - 1)) / sizeof(uint32_t) || + indirect_table_offset > dysymtab->nindirectsyms || + num_syms > dysymtab->nindirectsyms - indirect_table_offset) { + die("bad indirect section"); + } + + uint32_t *indirect_syms = rangeconv_off((range_t) {load, (addr_t) dysymtab->indirectsymoff + indirect_table_offset * sizeof(uint32_t), num_syms * sizeof(uint32_t)}, MUST_FIND).start; + void *addrs = rangeconv_off((range_t) {load, offset, size}, MUST_FIND).start; + for(uint32_t i = 0; i < num_syms; i++, indirect_syms++, addrs += stride) { + addr_t addr, found_addr; + + switch(*indirect_syms) { + case INDIRECT_SYMBOL_LOCAL: + if(mode == RELOC_EXTERN_ONLY || mode == RELOC_USERLAND) continue; + addr = read_pointer(addrs, pointer_size) + slide; + break; + case INDIRECT_SYMBOL_ABS: + continue; + default: + if(mode == RELOC_LOCAL_ONLY) continue; + found_addr = lookup_nth_symbol(load, *indirect_syms, lookup_sym, context, mode == RELOC_USERLAND); + if(!found_addr && mode == RELOC_USERLAND) { + // don't set to ABS! + continue; + } + + addr = found_addr; + break; + } + + write_pointer(addrs, addr, pointer_size); + *indirect_syms = INDIRECT_SYMBOL_ABS; + } + break; + } + case S_ZEROFILL: + case S_MOD_INIT_FUNC_POINTERS: + case S_MOD_TERM_FUNC_POINTERS: + case S_REGULAR: + case S_CSTRING_LITERALS: + case S_4BYTE_LITERALS: + case S_8BYTE_LITERALS: + case S_16BYTE_LITERALS: + break; + default: + if(mode != RELOC_USERLAND) { + die("unrecognized section type %02x", type); + } + } + +} + +static void relocate_with_symtab(struct binary *load, enum reloc_mode mode, lookupsym_t lookup_sym, void *context, addr_t slide) { + if(mode != RELOC_EXTERN_ONLY && mode != RELOC_USERLAND) { + relocate_area(load, load->mach->dysymtab->locreloff, load->mach->dysymtab->nlocrel, mode, lookup_sym, context, slide); + } + if(mode != RELOC_LOCAL_ONLY) { + relocate_area(load, load->mach->dysymtab->extreloff, load->mach->dysymtab->nextrel, mode, lookup_sym, context, slide); + } + + CMD_ITERATE(b_mach_hdr(load), cmd) { + MACHO_SPECIALIZE( + if(cmd->cmd == LC_SEGMENT_X) { + segment_command_x *seg = (void *) cmd; + //printf("%.16s %08x\n", seg->segname, seg->vmaddr); + section_x *sect = (void *) (seg + 1); + for(uint32_t i = 0; i < seg->nsects; i++, sect++) { + //printf(" %.16s\n", sect->sectname); + go_indirect(load, sect->offset, sect->size, sect->flags, sect->reserved1, sect->reserved2, mode, lookup_sym, context, slide); + relocate_area(load, sect->reloff, sect->nreloc, mode, lookup_sym, context, slide); + } + } + ) + } + +} + +static void do_bind_section(prange_t opcodes, struct binary *load, bool weak, bool userland, lookupsym_t lookup_sym, void *context) { + uint8_t pointer_size = b_pointer_size(load); + + uint8_t symbol_flags; + char *sym = NULL; + uint8_t type = BIND_TYPE_POINTER; + addr_t addend = 0; + prange_t segment = {NULL, 0}; + addr_t segaddr = 0; + addr_t offset = 0; + + void *ptr = opcodes.start, *end = ptr + opcodes.size; + while(ptr != end) { + void *orig_ptr = ptr; + uint8_t byte = read_int(&ptr, end, uint8_t); + uint8_t immediate = byte & BIND_IMMEDIATE_MASK; + uint8_t opcode = byte & BIND_OPCODE_MASK; + + addr_t count, stride; + + switch(opcode) { + case BIND_OPCODE_DONE: + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + // do nothing + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + read_uleb128(&ptr, end); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + sym = read_cstring(&ptr, end); + symbol_flags = immediate; + break; + case BIND_OPCODE_SET_TYPE_IMM: + type = immediate; + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + addend = read_sleb128(&ptr, end); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + if(immediate >= load->nsegments) { + die("segment too high"); + } + segment = rangeconv_off(load->segments[immediate].file_range, MUST_FIND); + segaddr = load->segments[immediate].vm_range.start; + offset = read_uleb128(&ptr, end); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + { + addr_t o = read_uleb128(&ptr, end); + offset += o; + } + break; + case BIND_OPCODE_DO_BIND: + count = 1; + stride = pointer_size; + goto bind; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + count = 1; + stride = read_uleb128(&ptr, end) + pointer_size; + goto bind; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + count = 1; + stride = immediate * pointer_size + pointer_size; + goto bind; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(&ptr, end); + stride = read_uleb128(&ptr, end) + pointer_size; + goto bind; + bind: { + if(!sym || !segment.start) die("improper bind"); + bool _64b; + addr_t value; + + + value = lookup_symbol_or_do_stuff(lookup_sym, context, sym, weak, userland); + if(!value) { + offset += stride * count; + break; + } + value += addend; + switch(type) { + case BIND_TYPE_POINTER: + _64b = pointer_size == 8; + break; + case BIND_TYPE_TEXT_ABSOLUTE32: + _64b = false; + break; + case BIND_TYPE_TEXT_PCREL32: + _64b = false; + value = -value + (segaddr + offset + 4); + break; + default: + die("bad bind type %d", (int) type); + } + + if(offset >= segment.size || + stride < (_64b ? sizeof(uint64_t) : sizeof(uint32_t)) || + (segment.size - offset) / stride < count) { + die("bad address while binding"); + } + + while(count--) { + if(_64b) { + *((uint64_t *) (segment.start + offset)) = value; + } else { + *((uint32_t *) (segment.start + offset)) = value; + } + + offset += stride; + if(type == BIND_TYPE_TEXT_PCREL32) value += stride; + } + + memset(orig_ptr, BIND_OPCODE_SET_TYPE_IMM, ptr - orig_ptr); + type = BIND_TYPE_POINTER; + break; + } + default: + die("unknown bind opcode 0x%x", (int) opcode); + } + } +} + +static void do_rebase(struct binary *load, prange_t opcodes, addr_t slide) { + uint8_t pointer_size = b_pointer_size(load); + uint8_t type = REBASE_TYPE_POINTER; + addr_t offset = 0; + prange_t segment = {NULL, 0}; + + void *ptr = opcodes.start, *end = ptr + opcodes.size; + while(ptr != end) { + uint8_t byte = read_int(&ptr, end, uint8_t); + uint8_t immediate = byte & BIND_IMMEDIATE_MASK; + uint8_t opcode = byte & BIND_OPCODE_MASK; + + addr_t count, stride; + + switch(opcode) { + // this code is very similar to do_bind_section + case REBASE_OPCODE_DONE: + return; + case REBASE_OPCODE_SET_TYPE_IMM: + type = immediate; + break; + case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + if(immediate >= load->nsegments) { + die("segment too high"); + } + segment = rangeconv_off(load->segments[immediate].file_range, MUST_FIND); + offset = read_uleb128(&ptr, end); + break; + case REBASE_OPCODE_ADD_ADDR_ULEB: + offset += read_uleb128(&ptr, end); + break; + case REBASE_OPCODE_ADD_ADDR_IMM_SCALED: + offset += immediate * pointer_size; + break; + case REBASE_OPCODE_DO_REBASE_IMM_TIMES: + count = immediate; + stride = pointer_size; + goto rebase; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES: + count = read_uleb128(&ptr, end); + stride = pointer_size; + goto rebase; + case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: + count = 1; + stride = read_uleb128(&ptr, end) + pointer_size; + goto rebase; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(&ptr, end); + stride = read_uleb128(&ptr, end) + pointer_size; + goto rebase; + rebase: { + bool _64b; + switch(type) { + case REBASE_TYPE_POINTER: + _64b = pointer_size == 8; + break; + case REBASE_TYPE_TEXT_ABSOLUTE32: + case REBASE_TYPE_TEXT_PCREL32: + _64b = false; + break; + default: + die("bad rebase type %d", (int) type); + } + + if(offset >= segment.size || (segment.size - offset) / stride < count) { + die("bad address while rebasing"); + } + + while(count--) { + if(_64b) { + *((uint64_t *) (segment.start + offset)) += slide; + } else { + uint32_t *ptr = segment.start + offset; + *ptr += slide; + if(type == REBASE_TYPE_TEXT_PCREL32) { + // WTF!? This is actually what dyld does. + *ptr = -*ptr; + } + } + + offset += stride; + } + break; + } + default: + die("unknown rebase opcode 0x%x", (int) opcode); + } + } +} + +static void relocate_with_dyld_info(struct binary *load, enum reloc_mode mode, lookupsym_t lookup_sym, void *context, addr_t slide) { + // It gets more complicated + struct dyld_info_command *dyld_info = load->mach->dyld_info; + #define fetch(type) prange_t type = dyld_info->type##_off ? rangeconv_off((range_t) {load, dyld_info->type##_off, dyld_info->type##_size}, MUST_FIND) : (prange_t) {NULL, 0}; + + if(mode != RELOC_EXTERN_ONLY && slide != 0) { + fetch(rebase) + do_rebase(load, rebase, slide); + dyld_info->rebase_size = 0; + } + + if(mode != RELOC_LOCAL_ONLY) { + fetch(bind) + fetch(weak_bind) + fetch(lazy_bind) + bool userland = mode == RELOC_USERLAND; + do_bind_section(bind, load, userland, userland, lookup_sym, context); + do_bind_section(weak_bind, load, true, userland, lookup_sym, context); + do_bind_section(lazy_bind, load, userland, userland, lookup_sym, context); + } +} + +void b_relocate(struct binary *load, const struct binary *target, enum reloc_mode mode, lookupsym_t lookup_sym, void *context, addr_t slide) { + if(mode == RELOC_USERLAND && slide != 0) { + die("sliding is not supported in userland mode"); + } + + if(!load->mach->symtab || !load->mach->dysymtab) { + die("no LC_SYMTAB/LC_DYSYMTAB"); + } + + // check for overlap + if(target) { + for(uint32_t i = 0; i < load->nsegments; i++) { + struct data_segment *a = &load->segments[i]; + for(uint32_t j = 0; j < target->nsegments; j++) { + struct data_segment *b = &target->segments[j]; + addr_t diff = b->vm_range.start - (a->vm_range.start + slide); + if(diff < a->vm_range.size || -diff < b->vm_range.size) { + die("segments of load and target overlap; load:%llx+%zu target:%llx+%zu", (uint64_t) a->vm_range.start, a->vm_range.size, (uint64_t) b->vm_range.start, b->vm_range.size); + } + } + } + } + + (load->mach->dyld_info ? relocate_with_dyld_info : relocate_with_symtab)(load, mode, lookup_sym, context, slide); + + if(mode != RELOC_EXTERN_ONLY && slide != 0) { + CMD_ITERATE(b_mach_hdr(load), cmd) { + MACHO_SPECIALIZE( + if(cmd->cmd == LC_SEGMENT_X) { + segment_command_x *seg = (void *) cmd; + section_x *sect = (void *) (seg + 1); + seg->vmaddr += slide; + for(uint32_t i = 0; i < seg->nsects; i++, sect++) { + sect->addr += slide; + } + } + ) + } + } +} + diff --git a/data/mach-o/link.h b/data/mach-o/link.h new file mode 100644 index 0000000..e674f08 --- /dev/null +++ b/data/mach-o/link.h @@ -0,0 +1,17 @@ +#pragma once +#include "binary.h" + +typedef addr_t (*lookupsym_t)(void *context, const char *sym); + +enum reloc_mode { + RELOC_DEFAULT, + RELOC_LOCAL_ONLY, + RELOC_EXTERN_ONLY, + RELOC_USERLAND +}; + +__BEGIN_DECLS + +void b_relocate(struct binary *load, const struct binary *target /* can be null to not check for overlap */, enum reloc_mode mode, lookupsym_t lookup_sym, void *context, addr_t slide); + +__END_DECLS diff --git a/data/mach-o/read_dyld_info.h b/data/mach-o/read_dyld_info.h new file mode 100644 index 0000000..4826c45 --- /dev/null +++ b/data/mach-o/read_dyld_info.h @@ -0,0 +1,56 @@ +#pragma once +#include +// ld64 +static addr_t read_xleb128(void **ptr, void *end, bool is_signed) { + addr_t result = 0; + uint8_t *p = *ptr; + uint8_t bit; + unsigned int shift = 0; + do { + if(p >= (uint8_t *) end) die("uleb128 overrun"); + bit = *p++; + addr_t k = bit & 0x7f; + // 0x0051 BIND_OPCODE_ADD_ADDR_ULEB(0xFFFFFFF8) + // the argument is a lie, it's actually 64 bits of fff, which overflows here + // it should just be sleb, but ... + //if(shift >= 8*sizeof(addr_t) || ((k << shift) >> shift) != k) die("uleb128 too big"); + if(shift < sizeof(addr_t) * 8) { + result |= k << shift; + } + shift += 7; + } while(bit & 0x80); + if(is_signed && (bit & 0x40)) { + result |= ~(((addr_t) 0) << shift); + } + *ptr = p; + return result; +} + +static addr_t read_uleb128(void **ptr, void *end) { + return read_xleb128(ptr, end, false); +} + +__attribute__((unused)) static addr_t read_sleb128(void **ptr, void *end) { + return read_xleb128(ptr, end, true); +} + +static inline void *read_bytes(void **ptr, void *end, size_t size) { + char *p = *ptr; + if((size_t) ((char *) end - p) < size) die("too big"); + *ptr = p + size; + return p; +} + +#define read_int(ptr, end, typ) *((typ *) read_bytes(ptr, end, sizeof(typ))) + +static inline char *read_cstring(void **ptr, void *end) { + // could use strnlen... + char *start = *ptr, *strend = start; + while(strend != end) { + if(!*strend++) { + *ptr = strend; + return start; + } + } + die("c string overflow"); +} diff --git a/data/running_kernel.c b/data/running_kernel.c new file mode 100644 index 0000000..bab18ac --- /dev/null +++ b/data/running_kernel.c @@ -0,0 +1,353 @@ +#ifdef __APPLE__ +#include "running_kernel.h" +#include "find.h" +#include "mach-o/link.h" +#include "mach-o/binary.h" +#include "mach-o/headers/loader.h" +#include "mach-o/headers/nlist.h" +#include +#include + +struct proc; +typedef int32_t sy_call_t(struct proc *, void *, int *); +typedef void sy_munge_t(const void *, void *); + +struct sysent { /* system call table */ + int16_t sy_narg; /* number of args */ + int8_t sy_resv; /* reserved */ + int8_t sy_flags; /* flags */ + sy_call_t *sy_call; /* implementing function */ + sy_munge_t *sy_arg_munge32; /* system call arguments munger for 32-bit process */ + sy_munge_t *sy_arg_munge64; /* system call arguments munger for 64-bit process */ + int32_t sy_return_type; /* system call return types */ + uint16_t sy_arg_bytes; /* Total size of arguments in bytes for + * 32-bit system calls + */ +}; +#define _SYSCALL_RET_INT_T 1 + +// end copied + +kern_return_t kr_assert_(kern_return_t kr, const char *name, int line) { + if(kr) { + die("result=%08x on line %d:\n%s", kr, line, name); + } + return kr; +} +#define kr_assert(x) kr_assert_((x), #x, __LINE__) + +mach_port_t get_kernel_task() { + static mach_port_t kernel_task; + if(!kernel_task) { + kr_assert(task_for_pid(mach_task_self(), 0, &kernel_task)); + } + return kernel_task; +} + +uint32_t b_allocate_from_running_kernel(const struct binary *binary) { + mach_port_t kernel_task = get_kernel_task(); + if(b_mach_hdr(binary)->flags & MH_PREBOUND) { + CMD_ITERATE(b_mach_hdr(binary), cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *seg = (void *) cmd; + if(seg->vmsize == 0) continue; + vm_address_t address = seg->vmaddr; + printf("prebound allocate %08x %08x\n", (unsigned int) address, (unsigned int) seg->vmsize); + kr_assert(vm_allocate(kernel_task, + &address, + seg->vmsize, + VM_FLAGS_FIXED)); + + assert(address == seg->vmaddr); + kr_assert(vm_wire(mach_host_self(), + kernel_task, + address, + seg->vmsize, + VM_PROT_READ)); + } + } + return 0; + } else { + // try to reserve some space + uint32_t slide; + for(slide = 0xf0000000; slide < 0xf0000000 + 0x01000000; slide += 0x10000) { + CMD_ITERATE(b_mach_hdr(binary), cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *seg = (void *) cmd; + if(seg->vmsize == 0) continue; + vm_address_t address = seg->vmaddr + slide; + printf("allocate %08x %08x for %.16s (slide=%x)\n", (int) address, (int) seg->vmsize, seg->segname, (int) slide); + kern_return_t kr = vm_allocate(kernel_task, + &address, + seg->vmsize, + VM_FLAGS_FIXED); + if(!kr) { + assert(address == seg->vmaddr + slide); + kr_assert(vm_wire(mach_host_self(), + kernel_task, + address, + seg->vmsize, + VM_PROT_READ)); + continue; + } + // Bother, it didn't work. So we need to increase the slide... + // But first we need to get rid of the gunk we did manage to allocate. + CMD_ITERATE(b_mach_hdr(binary), cmd2) { + if(cmd2 == cmd) break; + if(cmd2->cmd == LC_SEGMENT) { + struct segment_command *seg2 = (void *) cmd2; + printf("deallocate %08x %08x\n", (int) (seg2->vmaddr + slide), (int) seg2->vmsize); + kr_assert(vm_deallocate(kernel_task, + seg2->vmaddr + slide, + seg2->vmsize)); + } + } + goto try_another_slide; + } + } + // If we got this far, it worked! + goto it_worked; + try_another_slide:; + } + // But if we got this far, we ran out of slides to try. + die("we couldn't find anywhere to put this thing and that is ridiculous"); + it_worked:; + return slide; + } +} + + +void b_inject_into_running_kernel(struct binary *to_load, uint32_t sysent) { + // save sysent so unload can have it + b_mach_hdr(to_load)->filetype = sysent; + + mach_port_t kernel_task = get_kernel_task(); + + CMD_ITERATE(b_mach_hdr(to_load), cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *seg = (void *) cmd; + uint32_t fs = seg->filesize; + if(seg->vmsize < fs) fs = seg->vmsize; + // if prebound, slide = 0 + vm_offset_t of = (vm_offset_t) rangeconv_off((range_t) {to_load, seg->fileoff, seg->filesize}, MUST_FIND).start; + vm_address_t ad = seg->vmaddr; + while(fs > 0) { + // complete headbang. + //printf("(%.16s) reading %x %08x -> %08x\n", seg->segname, fs, (uint32_t) of, (uint32_t) ad); + uint32_t tocopy = 0xfff; + if(fs < tocopy) tocopy = fs; + kr_assert(vm_write(kernel_task, + ad, + of, + tocopy)); + fs -= tocopy; + of += tocopy; + ad += tocopy; + } + if(seg->vmsize > 0) { + // This really depends on nx_disabled... + kr_assert(vm_protect(kernel_task, + seg->vmaddr, + seg->vmsize, + true, + seg->maxprot & ~VM_PROT_EXECUTE)); + kr_assert(vm_protect(kernel_task, + seg->vmaddr, + seg->vmsize, + false, + seg->initprot & ~VM_PROT_EXECUTE)); + + vm_machine_attribute_val_t val = MATTR_VAL_CACHE_FLUSH; + kr_assert(vm_machine_attribute(kernel_task, + seg->vmaddr, + seg->vmsize, + MATTR_CACHE, + &val)); + } + } + } + + // okay, now do the fancy syscall stuff + // how do I safely dispose of this file? + int lockfd = open("/tmp/.syscall-11", O_RDWR | O_CREAT); + assert(lockfd > 0); + assert(!flock(lockfd, LOCK_EX)); + + struct sysent orig_sysent; + vm_size_t whatever; + kr_assert(vm_read_overwrite(kernel_task, + sysent + 11 * sizeof(struct sysent), + sizeof(struct sysent), + (vm_offset_t) &orig_sysent, + &whatever)); + + CMD_ITERATE(b_mach_hdr(to_load), cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *seg = (void *) cmd; + struct section *sections = (void *) (seg + 1); + for(uint32_t i = 0; i < seg->nsects; i++) { + struct section *sect = §ions[i]; + + if((sect->flags & SECTION_TYPE) == S_MOD_INIT_FUNC_POINTERS) { + void **things = rangeconv_off((range_t) {to_load, sect->offset, sect->size}, MUST_FIND).start; + for(uint32_t i = 0; i < sect->size / 4; i++) { + struct sysent my_sysent = { 1, 0, 0, things[i], NULL, NULL, _SYSCALL_RET_INT_T, 0 }; + printf("--> %p\n", things[i]); + kr_assert(vm_write(kernel_task, + (vm_address_t) sysent + 11 * sizeof(struct sysent), + (vm_offset_t) &my_sysent, + sizeof(struct sysent))); + syscall(11); + } + } + } + } + } + + kr_assert(vm_write(kernel_task, + sysent + 11 * sizeof(struct sysent), + (vm_offset_t) &orig_sysent, + sizeof(struct sysent))); + + assert(!flock(lockfd, LOCK_UN)); +} + +void unload_from_running_kernel(uint32_t addr) { + mach_port_t kernel_task = get_kernel_task(); + + vm_size_t whatever; + + autofree struct mach_header *hdr = malloc(0x1000); + if(vm_read_overwrite(kernel_task, + (vm_address_t) addr, + 0x1000, + (vm_offset_t) hdr, + &whatever) == KERN_INVALID_ADDRESS) { + die("invalid address %08x", addr); + } + kr_assert(vm_read_overwrite(kernel_task, + (vm_address_t) addr, + 0xfff, + (vm_offset_t) hdr, + &whatever)); + if(hdr->magic != MH_MAGIC) { + die("invalid header (wrong address?)"); + } + CMD_ITERATE(hdr, cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *seg = (void *) cmd; + struct section *sections = (void *) (seg + 1); + for(uint32_t i = 0; i < seg->nsects; i++) { + struct section *sect = §ions[i]; + + if((sect->flags & SECTION_TYPE) == S_MOD_TERM_FUNC_POINTERS) { + uint32_t sysent = hdr->filetype; // hurf durf + assert(sysent); + autofree void **things = malloc(sect->size); + kr_assert(vm_read_overwrite(kernel_task, + (vm_address_t) sect->addr, + sect->size, + (vm_offset_t) things, + &whatever)); + for(uint32_t i = 0; i < sect->size / 4; i++) { + struct sysent my_sysent = { 1, 0, 0, things[i], NULL, NULL, _SYSCALL_RET_INT_T, 0 }; + printf("--> %p\n", things[i]); + kr_assert(vm_write(kernel_task, + (vm_address_t) sysent + 11 * sizeof(struct sysent), + (vm_offset_t) &my_sysent, + sizeof(struct sysent))); + syscall(11); + } + } + } + } + } + + CMD_ITERATE(hdr, cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *seg = (void *) cmd; + if(seg->vmsize > 0) { + kr_assert(vm_deallocate(kernel_task, + seg->vmaddr, + seg->vmsize)); + } + } + } +} + +void b_running_kernel_load_macho(struct binary *binary) { + kern_return_t kr; + + mach_port_t kernel_task = get_kernel_task(); + + char hdr_buf[0xfff]; + struct mach_header *const hdr = (void *) hdr_buf; + + addr_t mh_addr; + vm_size_t size; + for(addr_t hugebase = 0x80000000; hugebase; hugebase += 0x40000000) { + for(addr_t pagebase = 0x1000; pagebase < 0x10000; pagebase += 0x1000) { + mh_addr = (vm_address_t) (hugebase + pagebase); + size = 0x1000; + // This will return either KERN_PROTECTION_FAILURE if it's a good address, and KERN_INVALID_ADDRESS otherwise. + // But if we use a shorter size, it will read if it's a good address, and /crash/ otherwise. + // So we do two. + kr = vm_read_overwrite(kernel_task, (vm_address_t) mh_addr, size, (vm_address_t) hdr_buf, &size); + if(kr == KERN_INVALID_ADDRESS) { + continue; + } else if(kr && kr != KERN_PROTECTION_FAILURE) { + die("unexpected error from vm_read_overwrite: %d", kr); + } + // ok, it's valid, but is it the actual header? + size = 0xfff; + kr_assert(vm_read_overwrite(kernel_task, (vm_address_t) mh_addr, size, (vm_address_t) hdr_buf, &size)); + if(hdr->magic == MH_MAGIC) { + printf("found running kernel at 0x%08llx\n", (long long) mh_addr); + goto ok; + } + } + } + die("didn't find the kernel anywhere"); + + ok:; + + binary->cputype = b_mach_hdr(binary)->cputype; + binary->cpusubtype = b_mach_hdr(binary)->cpusubtype; + + if(b_mach_hdr(binary)->sizeofcmds > size - sizeof(*b_mach_hdr(binary))) { + die("sizeofcmds is too big"); + } + addr_t maxoff = 0; + CMD_ITERATE(b_mach_hdr(binary), cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *scmd = (void *) cmd; + addr_t newmax = scmd->fileoff + scmd->filesize; + if(newmax > maxoff) maxoff = newmax; + } + } + + char *buf = malloc(maxoff); + + CMD_ITERATE(b_mach_hdr(binary), cmd) { + if(cmd->cmd == LC_SEGMENT) { + struct segment_command *scmd = (void *) cmd; + addr_t off = scmd->fileoff; + addr_t addr = scmd->vmaddr; + vm_size_t size = scmd->filesize; + // Well, uh, this sucks. But there's some block on reading. In fact, it's probably a bug that this works. + while(size > 0) { + vm_size_t this_size = (vm_size_t) size; + if(this_size > 0xfff) this_size = 0xfff; + kr_assert(vm_read_overwrite(kernel_task, (vm_address_t) addr, this_size, (vm_address_t) (buf + off), &this_size)); + + off += (addr_t) this_size; + addr += (addr_t) this_size; + size -= this_size; + } + } + } + + b_prange_load_macho(binary, (prange_t) {buf, maxoff}, 0, ""); +} + +#endif diff --git a/data/running_kernel.h b/data/running_kernel.h new file mode 100644 index 0000000..3927d5a --- /dev/null +++ b/data/running_kernel.h @@ -0,0 +1,19 @@ +#pragma once +#ifdef __APPLE__ +#include "common.h" +#include "binary.h" + +__BEGIN_DECLS + + +uint32_t b_allocate_from_running_kernel(const struct binary *to_load); +void b_inject_into_running_kernel(struct binary *to_load, uint32_t sysent); +void unload_from_running_kernel(uint32_t addr); +void b_running_kernel_load_macho(struct binary *binary); +#ifdef __MACH30__ +mach_port_t get_kernel_task(); +#endif +void b_prepare_running_kernel(const struct binary *binary); + +__END_DECLS +#endif