Crash reading bytes from getsectbyname

不打扰是莪最后的温柔 提交于 2019-12-18 11:59:57

问题


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;
}

回答1:


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).



来源:https://stackoverflow.com/questions/28978788/crash-reading-bytes-from-getsectbyname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!