view loader.c @ 0:075d70197fc2

add written files.
author taiki
date Sat, 02 Feb 2013 22:15:35 +0900
parents
children 1b796d0dd763
line wrap: on
line source

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <mach-o/loader.h>

#define NAME_MAX_LENGTH 128
#define MAX_SEGMENT_NUM 128


void option_reader(int argc, char *argv[], char *filename)
{
    int i;
    for (i=0; i<argc; i++) {
        if(argv[i][0] == '-') {
            if(strcmp(argv[i], "-name")==0) {
                i++;
                strncpy(filename ,argv[i], NAME_MAX_LENGTH);
                printf("read %s\n", filename);
            }
        } else {
            strncpy(filename ,argv[i], NAME_MAX_LENGTH);
        }
    }
}

int main(int argc, char*argv[])
{
    char filename[NAME_MAX_LENGTH];
    option_reader(argc, argv, filename);

    int fp;
    if ((fp = open(filename, O_RDONLY)) < 0) {
        fprintf(stderr, "can not open file\t: %s\n", filename);
        exit(1);
    }

    struct stat sb;
    fstat(fp, &sb);

    char *head = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fp, 0);

    struct mach_header_64 *mh64 = (struct mach_header_64 *)head;

    if (MH_MAGIC_64 != mh64->magic) {
       fprintf(stderr, "This is not mach header 64.\n");
       return 0;
    }

    printf("%s is 64bit Mach-O file.\n", filename);

    if (MH_EXECUTE != mh64->filetype) {
        fprintf(stderr, "This is not executable file.\n");
        return 0;
    }

    printf("%s is executable file.\n", filename);

    if (CPU_TYPE_X86_64 == mh64->cputype) printf("CPU : x86_64\n"); 

    int i = 0;
    int mh64_size = sizeof(struct mach_header_64);
    int lc_size = sizeof(struct load_command);
    for (;i < mh64->ncmds; i++) {
        struct load_command * lc = (struct load_command*)head + lc_size * i;
    }

    close(fp);

    return 0;
}