前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >多角度体会 Swift 方法派发

多角度体会 Swift 方法派发

作者头像
网罗开发
发布2021-10-19 15:33:21
5690
发布2021-10-19 15:33:21
举报
文章被收录于专栏:网罗开发网罗开发

我们知道 Swift 有三种方法派发方式:静态派发(直接派发)、VTable 派发(函数表派发)、消息派发。下面我们分别从 SIL 中间语言,以及汇编的角度体会 Swift 的方法派发方式。

问题引子

在展开正文之前,我们先来看一个问题:

有一个 Framework (仅有一个类和一个方法)和一个 Swift App 工程(调用该方法),代码如下,将 Framework编译后直接集成在 App 工程中:

代码语言:javascript
复制
// Framework
public class SwiftMethodDispatchTable {
    public func getMethodName() -> String {
        let name = "SwiftMethodDispatchTable"
        print("Method name: \(name)")
        return name
    }
}

// App,ViewController.swift
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        readMethodName()
    }
    func readMethodName() {
        let name = SwiftMethodDispatchTable().getMethodName()
        print("read method name:", name)
    }
}

我们如果将 Framework 中的 getMethodName 方法改个名字(getMethodName_new),重新编译,并将编译后的二进制文件(如下图所示)覆盖 App 工程中集成的 Framework 二进制文件,且 HeadersModules 目录保持不变,App 中调用的方法名称也保持不变(仍然是 getMethodName)。

那么问题来了: App 重新编译后执行结果是什么?

  1. 编译报错
  2. 运行时报错
  3. 正常运行

下面我们回到正题,最后我们再来回答这个问题。

SIL

我们先来看三个相似的类,它们都包含了使用不同派发方式的 getMethodName 方法,同时我们通过 printMethodName 方法来观察它们的派发方式区别:

  • 静态派发
代码语言:javascript
复制
final public class SwiftMethodDispatchStatic {
    public init() {}
    
    func printMethodName() -> String {
        let name = getMethodName()
        return name
    }
    
    public func getMethodName() -> String {
        let name = "SwiftMethodDispatchStatic"
        print("Method name: \(name)")
        return name
    }
}
  • vtable 派发
代码语言:javascript
复制
public class SwiftMethodDispatchTable {
    public init() {}
    
    func printMethodName() -> String {
        let name = getMethodName()
        return name
    }
    
    public func getMethodName() -> String {
        let name = "SwiftMethodDispatchTable"
        print("Method name: \(name)")
        return name
    }
}
  • 消息派发
代码语言:javascript
复制
public class SwiftMethodDispatchMessage {
    public init() {}
    
    func printMethodName() -> String {
        let name = getMethodName()
        return name
    }

    @objc dynamic public func getMethodName() -> String {
        let name = "SwiftMethodDispatchMessage"
        print("Method name: \(name)")
        return name
    }
}

下面我们分别生成 SIL 对比看看(命令行执行 swiftc -emit-silgen -O xxx.swift 生成,以下摘录关键部分)。

静态派发

代码语言:javascript
复制
// SwiftMethodDispatchStatic.printMethodName()
sil hidden [ossa] @$s25SwiftMethodDispatchStaticAAC05printB4NameSSyF : $@convention(method) (@guaranteed SwiftMethodDispatchStatic) -> @owned String {
// %0 "self"                                      // users: %3, %1
bb0(%0 : @guaranteed $SwiftMethodDispatchStatic):
  debug_value %0 : $SwiftMethodDispatchStatic, let, name "self", argno 1 // id: %1
  // function_ref SwiftMethodDispatchStatic.getMethodName()
  %2 = function_ref @$s25SwiftMethodDispatchStaticAAC03getB4NameSSyF : $@convention(method) (@guaranteed SwiftMethodDispatchStatic) -> @owned String // user: %3
  %3 = apply %2(%0) : $@convention(method) (@guaranteed SwiftMethodDispatchStatic) -> @owned String // users: %8, %5, %4
  debug_value %3 : $String, let, name "name"      // id: %4
  %5 = begin_borrow %3 : $String                  // users: %7, %6
  %6 = copy_value %5 : $String                    // user: %9
  end_borrow %5 : $String                         // id: %7
  destroy_value %3 : $String                      // id: %8
  return %6 : $String                             // id: %9
} // end sil function '$s25SwiftMethodDispatchStaticAAC05printB4NameSSyF'

sil_vtable [serialized] SwiftMethodDispatchStatic {
  #SwiftMethodDispatchStatic.init!allocator: (SwiftMethodDispatchStatic.Type) -> () -> SwiftMethodDispatchStatic : @$s25SwiftMethodDispatchStaticAACABycfC // SwiftMethodDispatchStatic.__allocating_init()
  #SwiftMethodDispatchStatic.deinit!deallocator: @$s25SwiftMethodDispatchStaticAACfD // SwiftMethodDispatchStatic.__deallocating_deinit
}

在以上的 SIL 中重点看这两行:

代码语言:javascript
复制
// function_ref SwiftMethodDispatchStatic.getMethodName()
%2 = function_ref @$s25SwiftMethodDispatchStaticAAC03getB4NameSSyF : $@convention(method) (@guaranteed SwiftMethodDispatchStatic) -> @owned String // user: %3

function_ref 关键字表明 getMethodName 方法是通过方法指针来调用的,并且通过符号 s25SwiftMethodDispatchStaticAAC03getB4NameSSyF 来定位方法地址,同时 sil_vtable 中也未包含该方法。

vtable 派发

代码语言:javascript
复制
// SwiftMethodDispatchTable.printMethodName()
sil hidden [ossa] @$s24SwiftMethodDispatchTableAAC05printB4NameSSyF : $@convention(method) (@guaranteed SwiftMethodDispatchTable) -> @owned String {
// %0 "self"                                      // users: %3, %2, %1
bb0(%0 : @guaranteed $SwiftMethodDispatchTable):
  debug_value %0 : $SwiftMethodDispatchTable, let, name "self", argno 1 // id: %1
  %2 = class_method %0 : $SwiftMethodDispatchTable, #SwiftMethodDispatchTable.getMethodName : (SwiftMethodDispatchTable) -> () -> String, $@convention(method) (@guaranteed SwiftMethodDispatchTable) -> @owned String // user: %3
  %3 = apply %2(%0) : $@convention(method) (@guaranteed SwiftMethodDispatchTable) -> @owned String // users: %8, %5, %4
  debug_value %3 : $String, let, name "name"      // id: %4
  %5 = begin_borrow %3 : $String                  // users: %7, %6
  %6 = copy_value %5 : $String                    // user: %9
  end_borrow %5 : $String                         // id: %7
  destroy_value %3 : $String                      // id: %8
  return %6 : $String                             // id: %9
} // end sil function '$s24SwiftMethodDispatchTableAAC05printB4NameSSyF'

sil_vtable [serialized] SwiftMethodDispatchTable {
  #SwiftMethodDispatchTable.init!allocator: (SwiftMethodDispatchTable.Type) -> () -> SwiftMethodDispatchTable : @$s24SwiftMethodDispatchTableAACABycfC // SwiftMethodDispatchTable.__allocating_init()
  #SwiftMethodDispatchTable.printMethodName: (SwiftMethodDispatchTable) -> () -> String : @$s24SwiftMethodDispatchTableAAC05printB4NameSSyF // SwiftMethodDispatchTable.printMethodName()
  #SwiftMethodDispatchTable.getMethodName: (SwiftMethodDispatchTable) -> () -> String : @$s24SwiftMethodDispatchTableAAC03getB4NameSSyF // SwiftMethodDispatchTable.getMethodName()
  #SwiftMethodDispatchTable.deinit!deallocator: @$s24SwiftMethodDispatchTableAACfD // SwiftMethodDispatchTable.__deallocating_deinit
}

vtable 的方式中,方法的引用方式就变成了:

代码语言:javascript
复制
%2 = class_method %0 : $SwiftMethodDispatchTable, #SwiftMethodDispatchTable.getMethodName : (SwiftMethodDispatchTable) -> () -> String, $@convention(method) (@guaranteed SwiftMethodDispatchTable) -> @owned String // user: %3

这里的 class_method 关键字表明 getMethodName 使用类对象方法的方式,即函数表的方式,通过 sil_vtable 中的信息也能印证这一点,SwiftMethodDispatchTable 类的 vtable 表包含了这个方法。

消息派发

代码语言:javascript
复制
// SwiftMethodDispatchMessage.printMethodName()
sil hidden [ossa] @$s26SwiftMethodDispatchMessageAAC05printB4NameSSyF : $@convention(method) (@guaranteed SwiftMethodDispatchMessage) -> @owned String {
// %0 "self"                                      // users: %3, %2, %1
bb0(%0 : @guaranteed $SwiftMethodDispatchMessage):
  debug_value %0 : $SwiftMethodDispatchMessage, let, name "self", argno 1 // id: %1
  %2 = objc_method %0 : $SwiftMethodDispatchMessage, #SwiftMethodDispatchMessage.getMethodName!foreign : (SwiftMethodDispatchMessage) -> () -> String, $@convention(objc_method) (SwiftMethodDispatchMessage) -> @autoreleased NSString // user: %3
  %3 = apply %2(%0) : $@convention(objc_method) (SwiftMethodDispatchMessage) -> @autoreleased NSString // user: %5
  // function_ref static String._unconditionallyBridgeFromObjectiveC(_:)
  %4 = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // user: %7
  %5 = enum $Optional<NSString>, #Optional.some!enumelt, %3 : $NSString // users: %9, %7
  %6 = metatype $@thin String.Type                // user: %7
  %7 = apply %4(%5, %6) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // users: %13, %10, %8
  debug_value %7 : $String, let, name "name"      // id: %8
  destroy_value %5 : $Optional<NSString>          // id: %9
  %10 = begin_borrow %7 : $String                 // users: %12, %11
  %11 = copy_value %10 : $String                  // user: %14
  end_borrow %10 : $String                        // id: %12
  destroy_value %7 : $String                      // id: %13
  return %11 : $String                            // id: %14
} // end sil function '$s26SwiftMethodDispatchMessageAAC05printB4NameSSyF'

sil_vtable [serialized] SwiftMethodDispatchMessage {
  #SwiftMethodDispatchMessage.init!allocator: (SwiftMethodDispatchMessage.Type) -> () -> SwiftMethodDispatchMessage : @$s26SwiftMethodDispatchMessageAACABycfC // SwiftMethodDispatchMessage.__allocating_init()
  #SwiftMethodDispatchMessage.printMethodName: (SwiftMethodDispatchMessage) -> () -> String : @$s26SwiftMethodDispatchMessageAAC05printB4NameSSyF // SwiftMethodDispatchMessage.printMethodName()
  #SwiftMethodDispatchMessage.deinit!deallocator: @$s26SwiftMethodDispatchMessageAACfD // SwiftMethodDispatchMessage.__deallocating_deinit
}

在消息派发中,引用方式变成了:

代码语言:javascript
复制
%2 = objc_method %0 : $SwiftMethodDispatchMessage, #SwiftMethodDispatchMessage.getMethodName!foreign : (SwiftMethodDispatchMessage) -> () -> String, $@convention(objc_method) (SwiftMethodDispatchMessage) -> @autoreleased NSString // user: %3

objc_method 关键字表明了方法已经转为了使用 OC 中的方法派发方式,即消息派发,并且方法签名中,返回类型已经变为了 NSString,vtable 中也没有了 getMethodName 方法。从 SIL 的角度看 Swift 中的方法派发方式,是不是很明白。

汇编

我们接着再从汇编层面看看以上几种派发方式的区别。

在开始前我们先准备点样例代码,在最前面的 App 工程中我们增加上面提到的几个方法:

代码语言:javascript
复制
@IBAction func StaticDispatch(_ sender: Any) {
        _ = SwiftMethodDispatchStatic().getMethodName()
    }
    
    @IBAction func VTableDispatch(_ sender: Any) {
        _ = SwiftMethodDispatchTable().getMethodName()
    }
    
    @IBAction func MessageDispatch(_ sender: Any) {
        _ = SwiftMethodDispatchMessage().getMethodName()
    }

我们在调用处打上断点,并通过汇编模式进行调试观察(选择 Debug 菜单中的 Debug Workflow,勾选 Always Show Disassembly):

下面我们分别看看不同派发方式中汇编代码的区别

静态派发

下面是 StaticDispatch 方法对应的汇编代码:

在第 17 行 bl 0x1047414cc 这条指令后有一个注解:symbol stub for …getMethodName...,可以猜想一定和 getMethodName 方法有关,那么我们看看 0x1047414c 这个地址到底指向什么。

bl 指令表示跳转到指定的子程序名处执行代码 symbol stub 表示代码的符号占位,实际代码要根据占位符号进行重新定位。

执行以下命令:

代码语言:javascript
复制
image lookup --address 0x1047414cc

结果如下:

代码语言:javascript
复制
Address: SwiftMethodDispatchAppDemo[0x00000001000054cc] (SwiftMethodDispatchAppDemo.__TEXT.__stubs + 36)
Summary: SwiftMethodDispatchAppDemo`symbol stub for: SwiftMethodDispatch.SwiftMethodDispatchStatic.getMethodName() -> Swift.String

这里我们可以看到地址 0x1047414cc 对应的偏移地址是 0x00000001000054cc,我们根据这个地址在 MachO 文件的 __TEXT,__stubs 这个 section 中进行查找。

我们使用 MachOView 这个工具来查看 app 的二进制文件信息

下载这个工程编译运行即可:https://github.com/emptyglass123/MachOView[1]

打开 MachOView 后我们在 TEXT 段中找 __TEXT,__stubs 这个 section,查找偏移地址为 000054cc 的记录:

对应的值是一串符号:_$s19SwiftMethodDispatch0abC6StaticC03getB4NameSSyF,经过 demangle 转换后得到的值为:

SwiftMethodDispatch.SwiftMethodDispatchStatic.getMethodName() -> Swift.String

这与 image lookup 命令得到的结果一致,因为 SwiftMethodDispatch 是一个动态库,以上符号需要在动态库中进行重定位,我们在 MachOView 中再打开 SwiftMethodDispatch

Symbol Table 中搜索符号:_$s19SwiftMethodDispatch0abC6StaticC03getB4NameSSyF,该符号对应的代码段偏移地址是:32F4

继续在 __TEXT,__text section 中查找 32F4 地址对应的记录,从下图中标记的这一行开始即是 getMethodName 这个方法:

在 Xcode 中调试 App 的汇编代码可以对比代码是一致的:

从上面的查找过程可以发现 Swift 方法在使用静态派发时,几乎是直接使用了方法的内存地址(因为是外部符号,需要经过动态库的符号重定位)。如果静态派发的方法存储在 App 的二进制文件中,则调用的地址即为方法的内存入口地址,无需任何转换(可以自行验证)。

vtable 派发

我们再看看 vtable 派发的情况,类似地通过断点查看汇编代码:

单步调试停止到第 16 行处,查看 x8 这个寄存器的值,在 Xcode 的debug 区执行命令:

register read x8

结果如下:

代码语言:javascript
复制
x8 = 0x0000000100c782a0  type metadata for SwiftMethodDispatch.SwiftMethodDispatchTable

ldr x8, [x8, #0x60] 这条命令表示把 x8 + 0x60 所在内存地址的数据(4字节)读取到 x8 寄存器中。

我们再看下 x8 + 0x60 的地址(0x0000000100c78300)是什么内容:

代码语言:javascript
复制
image lookup --address 0x0000000100c78300
Address: SwiftMethodDispatch[0x0000000000008300] (SwiftMethodDispatch.__DATA.__data + 160)
Summary: type metadata for SwiftMethodDispatch.SwiftMethodDispatchTable + 96

这里存储的是 SwiftMethodDispatchTable 这个类的 metadata 信息,内部具体结构还有待研究,不过可以知道的是对象定义的方法包含在其中。再通过 MachOView 查看 SwiftMethodDispatch 的二进制文件信息,定位偏移地址 0x8300 的内容:

可以看到 0x8300 这个地址的值指向了另外一个地址:2CCC(Data LO 中低位地址在前,高位地址在后)

再重新定位 0x2ccc 这个地址指向的值,这是一个函数的入口地址:

我们在 Xcode 中继续调试到 19 行,再进入调用栈,可以看到进入了 SwiftMethodDispatchTable.getMethodName() 方法,与上面看到的二进制汇编代码是一致的,通过 image lookup 查找偏移地址也是匹配的:

代码语言:javascript
复制
image lookup --address 0x100c72ccc
Address: SwiftMethodDispatch[0x0000000000002ccc] (SwiftMethodDispatch.__TEXT.__text + 152)
Summary: SwiftMethodDispatch`SwiftMethodDispatch.SwiftMethodDispatchTable.getMethodName() -> Swift.String at SwiftMethodDispatchTable.swift:18

到这一步已经成功调用到了 getMethodName 方法。

从上面的过程我们可以看到,基于函数表派发的方式,调用方法时提供的是类的 metadata 数据的偏移地址(0x60),基于这个偏移地址可以再次定位到方法的实际入口地址。可以认为经历了一个查表的过程,不过这张函数表在编译时已经确定了,Swift 动态库提供的 swiftmodule 接口文件已经足以在编译期定位方法在 metadata 中的偏移地址。

消息派发

最后我们再看下消息派发的汇编代码:

这次的代码较多一点,我们单步调试停在第 16 行处,查看并计算 x8 + 0xb80 指向的地址:

代码语言:javascript
复制
(lldb) register read x8
x8 = 0x0000000100bb0000  (void *)0x00000001020acb98: ObjectiveC._convertBoolToObjCBool(Swift.Bool) -> ObjectiveC.ObjCBool

(lldb) image lookup --address 100bb0b80
Address: SwiftMethodDispatchAppDemo[0x000000010000cb80] (SwiftMethodDispatchAppDemo.__DATA.__objc_selrefs + 128)
Summary: "getMethodName"

根据 cb80 这个偏移地址在 App 的二进制文件中查找:

可以看到这个地址保存的内容是一个指针,地址为 0x5A9C,再看看这个指针的内容是什么:

0x5A9C 指向的内容是一个字符串 getMethodName,其实 __TEXT,__objc_methname 这个 section 就是保存的 OC 方法 SEL 名称。

在 Xcode 中运行至 17 行,再读取 x8 寄存器的内容,可以看到结果也是 getMethodName 这个字符串:

在 Xcode 中可以看到第 19 行调用了 objc_msgSend 这个方法,我们进入方法调试:

走到第 16 行时停下,查看 x17 寄存器的值:

代码语言:javascript
复制
register read x17 
x17 = 0x0000000100c7387c  SwiftMethodDispatch`@objc SwiftMethodDispatch.SwiftMethodDispatchMessage.getMethodName() -> Swift.String at <compiler-generated>

这个地址即是 getMethodName 对应 OC 方法的入口地址:

代码语言:javascript
复制
image lookup --address 0x0000000100c7387c
Address: SwiftMethodDispatch[0x000000000000387c] (SwiftMethodDispatch.__TEXT.__text + 3144) Summary: SwiftMethodDispatch`@objc SwiftMethodDispatch.SwiftMethodDispatchMessage.getMethodName() -> Swift.String at

在动态库的 MachO 中可以查看:

可以看到 getMethodName 其实对应有 2 个方法,一个是 OC 版的,一个是 Swift 版的,在内存中是 2 个地址:

代码语言:javascript
复制
@objc SwiftMethodDispatch.SwiftMethodDispatchMessage.getMethodName() -> Swift.String
SwiftMethodDispatch.SwiftMethodDispatchMessage.getMethodName() -> Swift.String

在 Xcode 进入 16 行的 br x17 指令,可以看到已经进入了 getMethodName 方法(OC 版):

这就证实了对 getMethodName 方法的调用已经转换成了对 getMethodName 这个消息的发送,走的是 OC 的消息发送逻辑(由 Swift 编译生成的 OC 兼容版本),有兴趣可以看看 objc_msgSend 的汇编解析。

从上面的过程可以看到,在 Swift 中如果方法被标记为需要通过消息发送的方式执行,那么方法的 SEL 就会存储在二进制中的 __TEXT,__objc_methname 这个 section 中,在调用时通过 SEL 来查找对应的方法入口。

问题回顾

现在我们再回到最前面的问题,Swift 方法修改名称后,在不修改接口信息的情况下,还能调用吗。

根据 Swift 方法派发的特性,问题中 getMethodName 方法使用的是函数表派发,由于接口未改动,它的偏移地址是不变的,在 App 运行时编译都是能正常通过的,在运行时通过类的 metadata 的偏移地址直接定位到方法的入口地址,并未涉及到新方法名的重定位,因此改名后的方法可以顺利被执行。

但是如果稍作修改,在 getMethodName 源码的上方添加另一个方法,偏移地址就发生了改变,运行时就会执行新添加的方法,如果方法的参数类型与返回值不符则会报错,相符则仍然可以顺利执行。

Demo 工程

本文的 Demo 工程见 Github[2]

也可以在公众号后台回复“211015”快速打开链接。

参考资料

[1]

https://github.com/emptyglass123/MachOView: https://github.com/emptyglass123/MachOView

[2]

Github: https://github.com/pmtao/SwiftMethodDispatchDemo

-End-

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-10-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 网罗开发 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题引子
  • SIL
    • 静态派发
      • vtable 派发
        • 消息派发
        • 汇编
          • 静态派发
            • vtable 派发
              • 消息派发
              • 问题回顾
              • Demo 工程
                • 参考资料
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档