Created
June 26, 2024 22:14
-
-
Save stephancasas/364f8f73204143841d65be48eb04584d to your computer and use it in GitHub Desktop.
Extract embedded data from a MachO executable at runtime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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