Skip to content

Instantly share code, notes, and snippets.

@eagletmt
Created April 29, 2009 13:06
Show Gist options
  • Save eagletmt/103758 to your computer and use it in GitHub Desktop.
Save eagletmt/103758 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <assert.h>
void *find_function(char *obj, const char *name);
int main(void)
{
/* load object file into memory */
FILE *fp = fopen("add.o", "r");
assert(fp != NULL);
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *obj = malloc(fsize);
fread(obj, 1, fsize, fp);
fclose(fp);
int (*add)(int, int) = (int (*)(int, int))find_function(obj, "_add");
printf("%d\n", add(2, 4));
free(obj);
return 0;
}
void *find_function(char *obj, const char *name)
{
char *obj_p = obj;
/* check mach-o header */
struct mach_header *header = (struct mach_header *)obj_p;
obj_p += sizeof *header;
assert(header->magic == MH_MAGIC);
struct section *sections = NULL;
struct nlist *nl = NULL;
int i;
for (i = 0; i < header->ncmds; ++i) {
struct load_command *lc = (struct load_command *)obj_p;
if (lc->cmd == LC_SYMTAB) {
struct symtab_command *symtab = (struct symtab_command *)obj_p;
obj_p += sizeof *symtab;
struct nlist *ns = (struct nlist *)(obj + symtab->symoff);
char *strtable = obj + symtab->stroff;
/* find symbol's nlist */
int j;
for (j = 0; j < symtab->nsyms; ++j) {
if (strcmp(name, strtable + ns[j].n_un.n_strx) == 0) {
assert((ns[j].n_type & N_TYPE) == N_SECT);
nl = ns + j;
break;
}
}
}
else if (lc->cmd == LC_SEGMENT) {
struct segment_command *segment = (struct segment_command *)obj_p;
obj_p += sizeof *segment;
sections = (struct section *)obj_p;
obj_p += segment->nsects * sizeof *sections;
}
else {
/* skip */
obj_p += lc->cmdsize;
}
}
assert(sections != NULL);
assert(nl != NULL);
struct section *sect = sections + nl->n_sect-1; /* n_sect is 1-origin */
char *text = obj + sect->offset + nl->n_value;
return text;
}
@caihongxiaoyang
Copy link

This code cannot run on IOS, I think it is because the memory area where "obj" is located is the data segment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment