swift - 从 Swift 调用 getsectiondata

标签 swift macos mach-o

这个问题和答案描述了如何在现代 OS X/macOS 版本上使用 Objective-C 从 Mach-O 部分读取数据:Crash reading bytes from getsectbyname

所描述的答案有效。我正在尝试用 Swift 实现同样的事情。我做不到。

我在“其他链接器标志”中有以下内容:-Wl,-sectcreate,__LOCALIZATIONS,__base,en.lproj/Localizable.strings,-segprot,__LOCALIZATIONS,r,r .

这段 Swift 代码为我提供了一个指向嵌入数据的指针,直到我尝试在 Xcode 外部运行代码并且 ASLR 破坏了它:

var size: UInt = 0
let _localizationSection = getsectdata(
    "__LOCALIZATIONS",
    "__base",
    &size)

为了解决ASLR问题,根据上面的问答,根据我自己的测试,我应该使用getsectiondata反而。它在 Objective-C 中运行良好,但我在 Swift 中运气不佳。以下是我设法通过编译器的唯一内容,但它返回 nil:

var size: UInt = 0
var header = _mh_execute_header
let localizationSection = getsectiondata(
    &header,
    "__LOCALIZATIONS",
    "__base",
    &size)

正在复制 _mh_execute_header问题,有什么办法可以避免吗?我需要一个 UnsafePointer<mach_header_64> , 但使用 &_mh_execute_header作为 getsectiondata 的第一个参数导致编译错误。

我正在使用 Swift 3.0,并在 macOS 10.12 上运行我的代码。

最佳答案

链接到Objective-C代码的区别

void *ptr = getsectiondata(&_mh_execute_header, ...);

和你的 Swift 翻译

var header = _mh_execute_header
let localizationSection = getsectiondata(&header, ...)

是后者传递了全局的副本的地址 _mh_execute_header 函数的变量,显然 不被接受。如果将 Objective-C 代码修改为

struct mach_header_64 header = _mh_execute_header;
void *ptr = getsectiondata(&header, ...);

然后它也失败了(实际上在我的测试中崩溃了)。

现在的问题是 _mh_execute_header 暴露给了 Swift 作为一个常量:

public let _mh_execute_header: mach_header_64

而且在 Swift 中不能获取常量的地址。一种可能 解决方法是定义

#import <mach-o/ldsyms.h>
static const struct mach_header_64 *mhExecHeaderPtr = &_mh_execute_header;

在桥接头文件中,然后作为

let localizationSection = getsectiondata(mhExecHeaderPtr, ...)

在 Swift 中。


另一种选择是通过dlopen/dlsym查找符号

import MachO

if let handle = dlopen(nil, RTLD_LAZY) {
    defer { dlclose(handle) }

    if let ptr = dlsym(handle, MH_EXECUTE_SYM) {
        let mhExecHeaderPtr = ptr.assumingMemoryBound(to: mach_header_64.self)

        var size: UInt = 0
        let localizationSection = getsectiondata(
            mhExecHeaderPtr,
            "__LOCALIZATIONS",
            "__base",
            &size)

        // ...
    }
}

关于swift - 从 Swift 调用 getsectiondata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732016/

相关文章:

ios - 当我点击 swift 3 中的提交按钮时如何重复文本字段

ios - UIApplicationDelegate 但对于每个 ViewController

xcode - 如何使用 Xcode 创建动态库 (dylib)?

ios - 覆盖 iOS 框架符号

ios - App Extension 的 bundle ID 将一个帐户转移到另一个帐户

ios - 如何在 Swift 和 ObjectMapper 中使用继承?

cocoa - 单击 NSActionCell 时防止 NSOutlineView 中的选择发生更改

c - 伯克利套接字,运行简单的客户端和服务器连接

python - 如何在python中将网页转换为pdf,就像打印中的另存为pdf选项一样

macos - OS-X 上的 GNU 链接器-GAS