|
| 1 | +import Foundation |
| 2 | + |
| 3 | +class InterposeSubclass { |
| 4 | + |
| 5 | + private enum Constants { |
| 6 | + static let subclassSuffix = "InterposeKit_" |
| 7 | + } |
| 8 | + |
| 9 | + enum ObjCSelector { |
| 10 | + static let getClass = Selector((("class"))) |
| 11 | + } |
| 12 | + |
| 13 | + enum ObjCMethodEncoding { |
| 14 | + static let getClass = extract("#@:") |
| 15 | + |
| 16 | + private static func extract(_ string: StaticString) -> UnsafePointer<CChar> { |
| 17 | + return UnsafeRawPointer(string.utf8Start).assumingMemoryBound(to: CChar.self) |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + /// The object that is being hooked. |
| 22 | + let object: AnyObject |
| 23 | + |
| 24 | + /// Subclass that we create on the fly |
| 25 | + private(set) var dynamicClass: AnyClass |
| 26 | + |
| 27 | + /// If the class has been altered (e.g. via NSKVONotifying_ KVO logic) |
| 28 | + /// then perceived and actual class don't match. |
| 29 | + /// |
| 30 | + /// Making KVO and Object-based hooking work at the same time is difficult. |
| 31 | + /// If we make a dynamic subclass over KVO, invalidating the token crashes in cache_getImp. |
| 32 | + init(object: AnyObject) throws { |
| 33 | + self.object = object |
| 34 | + dynamicClass = type(of: object) // satisfy set to something |
| 35 | + dynamicClass = try getExistingSubclass() ?? createSubclass() |
| 36 | + } |
| 37 | + |
| 38 | + private func createSubclass() throws -> AnyClass { |
| 39 | + let perceivedClass: AnyClass = type(of: object) |
| 40 | + let actualClass: AnyClass = object_getClass(object)! |
| 41 | + |
| 42 | + let className = NSStringFromClass(perceivedClass) |
| 43 | + // Right now we are wasteful. Might be able to optimize for shared IMP? |
| 44 | + let uuid = UUID().uuidString.replacingOccurrences(of: "-", with: "") |
| 45 | + let subclassName = Constants.subclassSuffix + className + uuid |
| 46 | + |
| 47 | + let subclass: AnyClass? = subclassName.withCString { cString in |
| 48 | + // swiftlint:disable:next force_cast |
| 49 | + if let existingClass = objc_getClass(cString) as! AnyClass? { |
| 50 | + return existingClass |
| 51 | + } else { |
| 52 | + guard let subclass: AnyClass = objc_allocateClassPair(actualClass, cString, 0) else { return nil } |
| 53 | + replaceGetClass(in: subclass, decoy: perceivedClass) |
| 54 | + objc_registerClassPair(subclass) |
| 55 | + return subclass |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + guard let nonnullSubclass = subclass else { |
| 60 | + throw InterposeError.failedToAllocateClassPair(class: perceivedClass, subclassName: subclassName) |
| 61 | + } |
| 62 | + |
| 63 | + object_setClass(object, nonnullSubclass) |
| 64 | + Interpose.log("Generated \(NSStringFromClass(nonnullSubclass)) for object (was: \(NSStringFromClass(class_getSuperclass(object_getClass(object)!)!)))") |
| 65 | + return nonnullSubclass |
| 66 | + } |
| 67 | + |
| 68 | + /// We need to reuse a dynamic subclass if the object already has one. |
| 69 | + private func getExistingSubclass() -> AnyClass? { |
| 70 | + let actualClass: AnyClass = object_getClass(object)! |
| 71 | + if NSStringFromClass(actualClass).hasPrefix(Constants.subclassSuffix) { |
| 72 | + return actualClass |
| 73 | + } |
| 74 | + return nil |
| 75 | + } |
| 76 | + |
| 77 | + #if !os(Linux) |
| 78 | + private func replaceGetClass(in class: AnyClass, decoy perceivedClass: AnyClass) { |
| 79 | + // crashes on linux |
| 80 | + let getClass: @convention(block) (AnyObject) -> AnyClass = { _ in |
| 81 | + perceivedClass |
| 82 | + } |
| 83 | + let impl = imp_implementationWithBlock(getClass as Any) |
| 84 | + _ = class_replaceMethod(`class`, ObjCSelector.getClass, impl, ObjCMethodEncoding.getClass) |
| 85 | + _ = class_replaceMethod(object_getClass(`class`), ObjCSelector.getClass, impl, ObjCMethodEncoding.getClass) |
| 86 | + } |
| 87 | + |
| 88 | + class var supportsSuperTrampolines: Bool { |
| 89 | + NSClassFromString("SuperBuilder")?.value(forKey: "isSupportedArchitecure") as? Bool ?? false |
| 90 | + } |
| 91 | + |
| 92 | + private lazy var addSuperImpl: @convention(c) (AnyClass, Selector, NSErrorPointer) -> Bool = { |
| 93 | + let handle = dlopen(nil, RTLD_LAZY) |
| 94 | + let imp = dlsym(handle, "IKTAddSuperImplementationToClass") |
| 95 | + return unsafeBitCast(imp, to: (@convention(c) (AnyClass, Selector, NSErrorPointer) -> Bool).self) |
| 96 | + }() |
| 97 | + |
| 98 | + func addSuperTrampoline(selector: Selector) { |
| 99 | + var error: NSError? |
| 100 | + if addSuperImpl(dynamicClass, selector, &error) == false { |
| 101 | + Interpose.log("Failed to add super implementation to -[\(dynamicClass).\(selector)]: \(error!)") |
| 102 | + } else { |
| 103 | + let imp = class_getMethodImplementation(dynamicClass, selector)! |
| 104 | + Interpose.log("Added super for -[\(dynamicClass).\(selector)]: \(imp)") |
| 105 | + } |
| 106 | + } |
| 107 | + #else |
| 108 | + func addSuperTrampoline(selector: Selector) { } |
| 109 | + class var supportsSuperTrampolines: Bool { return false } |
| 110 | + private func replaceGetClass(in class: AnyClass, decoy perceivedClass: AnyClass) {} |
| 111 | + #endif |
| 112 | +} |
0 commit comments