Question

I trying to read the mach header for some executables under osx 10.7.4. In many cases the header magic field isn't equal to MH_MAGIC so I'm guessing these binaries uses a different format? So the question is what fileformats is used for executables files under MAC osx?

 int main(int argc, char** argv) {
    char* path = getenv("PATH");
    char* token = strtok(path, ":");
    char filename[260];
    DIR* pdir = NULL;
    dirent* pentry = NULL;
    FILE* fin = NULL;
    mach_header header;
    // loop through each directory set in path
    while(token) {
       // try to open directory
       pdir = opendir(token);
       if(pdir) {
         // read entry from directory
         while((pentry = readdir(pdir))) {
            // check so it's a regular file
            if(pentry->d_type == DT_REG) {
               sprintf(filename, "%s/%s", token, pentry->d_name);
               // try to open file and read mach header
               fin = fopen(filename, "r");
               if(fin) { 
                  fread(&header, sizeof(header), 1, fin);   
                  if(header.magic == MH_MAGIC) {    
                     printf("%s has a mach-o header\n", filename);
                  }
                  fclose(fin);
               }
            }
         }
         closedir(pdir);
       }
       token = strtok(NULL, ":");
    }
    return 0;
  }
Was it helpful?

Solution

Apart from Mach-O binaries themselves there are Fat Binaries which contain multiple architectures which are used to support Universal binaries. These have a different magic number. As far as I can tell the following magic numbers are currently in use in Mach-O (from my own code):

const uint8_t magic1[4] = { 0xce, 0xfa, 0xed, 0xfe };   // 32-bit
const uint8_t magic2[4] = { 0xca, 0xfe, 0xba, 0xbe };   // Universal
const uint8_t magic3[4] = { 0xcf, 0xfa, 0xed, 0xfe };   // 64-bit
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top