Skip to content

Instantly share code, notes, and snippets.

@stephancasas
Created June 26, 2024 22:14
Show Gist options
  • Save stephancasas/364f8f73204143841d65be48eb04584d to your computer and use it in GitHub Desktop.
Save stephancasas/364f8f73204143841d65be48eb04584d to your computer and use it in GitHub Desktop.
Extract embedded data from a MachO executable at runtime.
//
// Bundle+EmbeddedData.swift
//
//
// Created by Stephan Casas on 6/26/24.
//
import Foundation;
extension Bundle {
/// Get the raw bytes of an executable-embedded entity stored in the given segment and identified by the given section.
/// - Parameters:
/// - section: The name of the section in which the entity is stored.
/// - segment: The name of the segment in which the section is partitioned.
/// - Returns: The embedded entity's raw bytes as `Data`.
static func getEmbeddedDataForSection(_ section: String, in segment: String = "__TEXT") -> Data? {
guard let ownExecPtr = dlopen(nil, RTLD_NOW) else {
return nil;
}
defer { dlclose(ownExecPtr) }
guard let machHeaderOpaquePtr = dlsym(ownExecPtr, MH_EXECUTE_SYM) else {
return nil;
}
let machHeaderPtr = machHeaderOpaquePtr.assumingMemoryBound(
to: mach_header_64.self);
var dataSize: UInt = 0;
guard let dataPtr = getsectiondata(machHeaderPtr, segment, section, &dataSize) else {
return nil;
}
return .init(bytes: dataPtr, count: .init(dataSize));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment