Search code examples
macoscocoabundlemacos-carboncore-foundation

Loading and executing bundle from memory


Loading bundle from memory is possible by NSCreateObjectFileImageFromMemory function. Does anyone have successful experience in this area? Does anyone have working sample for this function? My code is as:

text srcPath = "/Applications/TextEdit.app/Contents/MacOS/TextEdit";
data_t data;
data.loadFromFile(srcPath);
void *addr;
kern_return_t err;
NSObjectFileImage img = nil;
NSObjectFileImageReturnCode dyld_err;

err = vm_allocate(mach_task_self(), (vm_address_t *)&addr,
    data.length(), true);
if(err == 0)
{
    //err = vm_write(mach_task_self(), (vm_address_t)addr,
        //(vm_address_t)(char*)data, data.length());
    memcpy(addr, (char*)data, data.length());
    if(err == 0)
        dyld_err =
            NSCreateObjectFileImageFromMemory(addr, data.length(), &img);
        // error is NSObjectFileImageFailure
}

The img variable is null (error is NSObjectFileImageFailure). Why?

Thankyou.


Solution

  • From the manpage, it looks like only MH_BUNDLE files can be loaded with NSCreateObjectFileImageFromMemory() and friends.

    MH_BUNDLE files are explained here.

    The MH_BUNDLE file type is the type typically used by code that you load at runtime (typically called bundles or plug-ins). By convention, the file name extension for this format is .bundle.

    Note that that manpage is for 10.4 and there does not appear to be a newer version available.