Slide 1

Slide 1 text

SWIFT FUNTIME ! ALTCONF, JUNE 2015 BORIS BÜGLING - @NEONACHO

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

CONTENTFUL

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

!

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

WHAT IS A SWIFT OBJECT EVEN?

Slide 9

Slide 9 text

IT DEPENDS

Slide 10

Slide 10 text

class MyObject : NSObject { }

Slide 11

Slide 11 text

â–¸ behaves like any old Objective-C object â–¸ instance variables are properties â–¸ fully interopable with ObjC

Slide 12

Slide 12 text

import ObjectiveC.runtime !

Slide 13

Slide 13 text

class MyObject { }

Slide 14

Slide 14 text

â–¸ has SwiftObject as superclass â–¸ instance variables are ivars only â–¸ ivars have no type encoding â–¸ methods are not ObjC methods â–¸ not interoperable with ObjC

Slide 15

Slide 15 text

SWIFTOBJECT Ivar: magic {SwiftObject_s="isa"^v"refCount"q} Protocol: NSObject NSOBJECT Ivar: isa # Protocol: NSObject

Slide 16

Slide 16 text

HOW DOES BRIDGING WORK, THEN?

Slide 17

Slide 17 text

IT DOESN'T

Slide 18

Slide 18 text

func info(x: T) { print("\(x) is a \(_stdlib_getDemangledTypeName(x))") } let array = [0, 1, 2] // 'as AnyObject' => ! info(array) // is a Swift.Array import Foundation let objc_array: AnyObject = [0, 1, 2] as AnyObject info(objc_array) // is a Swift._NSSwiftArrayImpl // comparing different array types => compiler error as well //let equal = objc_array == array

Slide 19

Slide 19 text

!

Slide 20

Slide 20 text

SWIFT 2.0 ./foo.swift:3:17: error: 'CFunctionPointer' is unavailable: use a function type '@convention(c) (T) -> U' typealias foo = CFunctionPointer<() -> ()>

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

@convention(swift) Apply this attribute to the type of the function to indicate its calling conventions.

Slide 23

Slide 23 text

C FUNCTION POINTERS SWIFT 1.X CFunctionPointer<(UnsafeMutablePointer, Float) -> Int>.self SWIFT 2.X typealias CFunction = @convention(c) (UnsafeMutablePointer, Float) -> Int CFunction.self

Slide 24

Slide 24 text

OBJECTIVE-C BLOCKS SWIFT 1.X @objc_block ... SWIFT 2.X @convention(block)

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

Y DID WE ! THE OBJECTIVE-" RUNTIME? â–¸ Dynamic Introspection ! â–¸ Change Behaviour "# â–¸ Analyse private API $

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

DYNAMIC INTROSPECTION

Slide 29

Slide 29 text

var propertyCount : UInt32 = 0 var properties : UnsafeMutablePointer = class_copyPropertyList(myClass, &propertyCount) for i in 0..

Slide 30

Slide 30 text

IN PURE SWIFT => !

Slide 31

Slide 31 text

THERE IS HOPE // Excerpt from the standard library /// How children of this value should be presented in the IDE. enum MirrorDisposition { case Struct case Class case Enum [...] } /// A protocol that provides a reflection interface to an underlying value. protocol MirrorType { [...] }

Slide 32

Slide 32 text

infix operator --> {} func --> (instance: Any, key: String) -> Any? { let mirror = reflect(instance) for index in 0 ..< mirror.count { let (childKey, childMirror) = mirror[index] if childKey == key { return childMirror.value } } return nil }

Slide 33

Slide 33 text

struct MyPoint { let x: Float let y: Float } let point = MyPoint(x: 1, y: 2) print(point --> "x") // Optional(1.0) print(point --> "y") // Optional(2.0)

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

CHANGE BEHAVIOUR

Slide 36

Slide 36 text

let myString = "foobar" as NSString print(myString.description) // foobar let myBlock : @convention(block) (AnyObject!) -> String = { (sself : AnyObject!) -> (String) in "✋" } let myIMP = imp_implementationWithBlock(unsafeBitCast(myBlock, AnyObject.self)) let method = class_getInstanceMethod(myString.dynamicType, "description") method_setImplementation(method, myIMP) print(myString.description) // ✋

Slide 37

Slide 37 text

NSINVOCATION DOES NOT EXIST

Slide 38

Slide 38 text

WHAT ABOUT PURE SWIFT?

Slide 39

Slide 39 text

SWROUTE â–¸ PoC of function hooking in Swift â–¸ Uses rd_route, a Mach specific injection library for C

Slide 40

Slide 40 text

#include #define kObjectFieldOffset sizeof(uintptr_t) struct swift_func_object { uintptr_t *original_type_ptr; #if defined(__x86_64__) uintptr_t *unknown0; #else uintptr_t *unknown0, *unknown1; #endif uintptr_t function_address; uintptr_t *self; };

Slide 41

Slide 41 text

uintptr_t _rd_get_func_impl(void *func) { struct swift_func_object *obj = (struct swift_func_object *) *(uintptr_t *)(func + kObjectFieldOffset); return obj->function_address; }

Slide 42

Slide 42 text

No content

Slide 43

Slide 43 text

LET'S DO THAT IN SWIFT

Slide 44

Slide 44 text

MEMORY LAYOUT â–¸ 8 bytes => Pointer to _TPA__TTRXFo_dSidSi_dSi_XFo_iTSiSi__iSi_ â–¸ 8 bytes => Pointer to struct _TPA__TTRXFo_dSidSi_dSi_XFo_iTSiSi__iSi_ ---> partial apply forwarder for reabstraction thunk helper [...]

Slide 45

Slide 45 text

MEMORY LAYOUT â–¸ 16 bytes => Swift object â–¸ 8 bytes => Pointer to _TF6memory3addFTSiSi_Si Function pointer !

Slide 46

Slide 46 text

struct f_trampoline { var trampoline_ptr: COpaquePointer var function_obj_ptr: UnsafeMutablePointer } struct function_obj { var some_ptr_0: COpaquePointer var some_ptr_1: COpaquePointer var function_ptr: COpaquePointer }

Slide 47

Slide 47 text

@asmname("floor") func my_floor(dbl: Double) -> Double print(my_floor(6.7)) let handle = dlopen(nil, RTLD_NOW) let pointer = COpaquePointer(dlsym(handle, "ceil")) typealias FunctionType = (Double) -> Double

Slide 48

Slide 48 text

struct f_trampoline { [...] } struct function_obj { [...] } let orig = unsafeBitCast(my_floor, f_trampoline.self) let new = f_trampoline(prototype: orig, new_fp: pointer) let my_ceil = unsafeBitCast(new, FunctionType.self) print(my_ceil(6.7))

Slide 49

Slide 49 text

$ xcrun swift -Onone hook.swift 6.0 7.0

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

CAN WE DO THIS THE OTHER WAY AROUND?

Slide 52

Slide 52 text

void executeFunction(void(*f)(void)) { f(); } typealias CFunc = @convention(c) ()->() @asmname("executeFunction") func executeFunction(fp: CFunc)

Slide 53

Slide 53 text

func greeting() { print("Hello from Swift") } typealias CFunc = @convention(c) ()->() let t = unsafeBitCast(greeting, f_trampoline.self) let fp = unsafeBitCast(t.function_obj_ptr.memory.function_ptr, CFunc.self) executeFunction(fp) Hello from Swift Program ended with exit code: 0

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

ANALYSE PRIVATE API

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

class MyClass { var someVar = 1 func someFuncWithAReallyLongNameLol() { } }

Slide 58

Slide 58 text

$ xcrun swiftc f.swift $ ./swift-dump.rb f // Code generated from `f` import Foundation class MyClass { var someVar: Int = 0 func someFuncWithAReallyLongNameLol() -> () {} }

Slide 59

Slide 59 text

$ xcrun nm -g f|grep TFC 0000000100000c50 T __TFC1f7MyClass30someFuncWithAReallyLongNameLolfS0_FT_T_ 0000000100000d30 T __TFC1f7MyClassCfMS0_FT_S0_ 0000000100000c70 T __TFC1f7MyClassD 0000000100000d10 T __TFC1f7MyClasscfMS0_FT_S0_ 0000000100000c60 T __TFC1f7MyClassd 0000000100000ca0 T __TFC1f7MyClassg7someVarSi 0000000100000ce0 T __TFC1f7MyClassm7someVarSi 0000000100000cc0 T __TFC1f7MyClasss7someVarSi

Slide 60

Slide 60 text

$ xcrun swift-demangle __TFC1f7MyClassg7someVarSi _TFC1f7MyClassg7someVarSi ---> f.MyClass.someVar.getter : Swift.Int

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

performSelector? import Foundation import ObjectiveC.runtime @asmname("objc_msgSend") func sendPerformSelector(NSObject, Selector, Selector) -> NSString extension NSObject { public func performSelector2(selector : Selector) -> NSString { return sendPerformSelector(self, "performSelector:", selector) } } let string : NSString = "Fuck yeah, Swift!" println(string.performSelector2("description"))

Slide 63

Slide 63 text

! 1. While emitting IR SIL function @_TFE15PerformSelectorCSo8NSObject16performSelector2fS0_FV10ObjectiveC8SelectorCSo8NSString for 'performSelector2' at ./PerformSelector.swift:13:12 Abort trap: 6

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

ONLY WORKS WITH SWIFT 1.1 :( #!/usr/bin/env DEVELOPER_DIR=/Applications/Xcode-6.2.app/Contents/Developer xcrun swift

Slide 66

Slide 66 text

$ ./PerformSelector.swift Fuck yeah, Swift

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

WHY func performSelector2 ? $ ./PerformSelector.swift Segmentation fault: 11

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

HOW ARE EMOJI FORMED? $ echo 'class ! {}'|xcrun swiftc -emit-library -o test - $ nm -g test ... 0000000000000db0 T __TFC4testX4ypIhD ... $ xcrun swift-demangle __TFC4testX4ypIhD _TFC4testX4ypIhD ---> test.!.__deallocating_deinit X4 ypIh ~ xn--yp8h

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

WHAT HAVE WE LEARNED? ▸ import ObjectiveC.runtime ☺ ▸ Introspection somewhat exists " ▸ Changing behaviour is hard # ▸ Reverse engineering is still fine $

Slide 73

Slide 73 text

THANK YOU!

Slide 74

Slide 74 text

â–¸ http://airspeedvelocity.net/ â–¸ http://www.russbishop.net/swift-how-did-i-do-horrible-things â–¸ https://github.com/mikeash/memorydumper â–¸ https://github.com/rodionovd/SWRoute

Slide 75

Slide 75 text

@NeoNacho [email protected] http://buegling.com/talks http://www.contentful.com