Crash reading bytes from getsectbyname
Asked Answered
C

1

11

UPDATE: Answer below in question, thanks to Greg Parker's pointer…

I uploaded a sample project here, but I'll describe it as well: https://github.com/tewha/getsectbyname-crash

I get a crash from my my (64-bit only) executable, but not when run from Xcode. If I run it from Terminal or Instruments, however, it crashes.

This is not a Debug vs. Release configuration problem; running the Debug executable in Terminal also crashes. Running the Release executable from Xcode works.

I am trying to read a inflict section from the Mach-O executable, linked into the app via CREATE_INFOPLIST_SECTION_IN_BINARY = YES.

const struct section_64 *plistSection = getsectbyname("__TEXT", "__info_plist");
NSLog(@"Found a section %s, %s", plistSection->segname, plistSection->sectname);
void *ptr = ((void *)plistSection->addr);
uint64_t size = plistSection->size;

NSLog(@"It has %zd bytes at %tx", size, plistSection->addr);
NSLog(@"Allocating %zd bytes", size);
void *buffer = malloc(size);
NSLog(@"Moving %zd bytes", size);
NSLog(@"(Crashes when doing the memmove.)");
memmove(buffer, ptr, size);
NSLog(@"Freeing %zd bytes", size);
free(buffer);

The output looks like this (I've simplified this a bit to remove date/time stamps, process IDs):

bash-4.3$ ./getsectbyname 
getsectbyname Found a section __TEXT, __info_plist
getsectbyname It has 658 bytes at 100000d07
getsectbyname Allocating 658 bytes
getsectbyname Moving 658 bytes
getsectbyname (Crashes when doing the memmove.)
Segmentation fault: 11

Can anyone tell me how to fix this?

The answer:

#import <Foundation/Foundation.h>

#include <mach-o/getsect.h>
#include <mach-o/ldsyms.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSError *e;
        unsigned long size;
        void *ptr = getsectiondata(&_mh_execute_header, "__TEXT",
                      "__info_plist", &size);
        NSData *plistData = [NSData dataWithBytesNoCopy:ptr length:size
                      freeWhenDone:NO];
        NSPropertyListFormat format;
        NSDictionary *infoPlistContents =
            [NSPropertyListSerialization propertyListWithData:plistData
             options:NSPropertyListImmutable format:&format error:&e];
        NSLog(@"The value for Key is %@", infoPlistContents[@"Key"]);
    }
    return 0;
}
Clomp answered 11/3, 2015 at 4:50 Comment(1)
I posted a question about doing the same thing in Swift: #39732516 . Any help appreciated.Nellynelms
E
13

getsectbyname() does not adjust the section's address for ASLR. You should use getsectiondata() instead if your deployment target allows (first implemented in OS X 10.7, I think).

Edessa answered 11/3, 2015 at 5:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.