├── .gitignore ├── LICENSE ├── Package.swift ├── README.md └── Sources └── ProfileSwiftUI └── ProfileSwiftUI.swift /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## User settings 6 | xcuserdata/ 7 | 8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 9 | *.xcscmblueprint 10 | *.xccheckout 11 | 12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 13 | build/ 14 | DerivedData/ 15 | *.moved-aside 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | 28 | ## App packaging 29 | *.ipa 30 | *.dSYM.zip 31 | *.dSYM 32 | 33 | ## Playgrounds 34 | timeline.xctimeline 35 | playground.xcworkspace 36 | 37 | # Swift Package Manager 38 | # 39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 40 | # Packages/ 41 | # Package.pins 42 | Package.resolved 43 | # *.xcodeproj 44 | # 45 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 46 | # hence it is not needed unless you have added a package configuration file to your project 47 | .swiftpm 48 | 49 | .build/ 50 | 51 | # CocoaPods 52 | # 53 | # We recommend against adding the Pods directory to your .gitignore. However 54 | # you should judge for yourself, the pros and cons are mentioned at: 55 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 56 | # 57 | # Pods/ 58 | # 59 | # Add this line if you want to avoid checking in source code from the Xcode workspace 60 | # *.xcworkspace 61 | 62 | # Carthage 63 | # 64 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 65 | # Carthage/Checkouts 66 | 67 | Carthage/Build/ 68 | 69 | # Accio dependency management 70 | Dependencies/ 71 | .accio/ 72 | 73 | # fastlane 74 | # 75 | # It is recommended to not store the screenshots in the git repo. 76 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 77 | # For more information about the recommended setup visit: 78 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 79 | 80 | fastlane/report.xml 81 | fastlane/Preview.html 82 | fastlane/screenshots/**/*.png 83 | fastlane/test_output 84 | 85 | # Code Injection 86 | # 87 | # After new code Injection tools there's a generated folder /iOSInjectionProject 88 | # https://github.com/johnno1962/injectionforxcode 89 | 90 | iOSInjectionProject/ 91 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 John Holdsworth 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.0 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "ProfileSwiftUI", 8 | platforms: [.macOS("10.12"), .iOS("10.0"), .tvOS("10.0")], 9 | products: [ 10 | // Products define the executables and libraries a package produces, making them visible to other packages. 11 | .library( 12 | name: "ProfileSwiftUI", 13 | targets: ["ProfileSwiftUI"]), 14 | ], 15 | dependencies: [ 16 | .package(url: "https://github.com/johnno1962/SwiftTrace", 17 | .upToNextMajor(from: "8.6.0")), 18 | .package(url: "https://github.com/johnno1962/SwiftRegex5", 19 | .upToNextMajor(from: "6.1.0")), 20 | .package(url: "https://github.com/johnno1962/DLKit", 21 | .upToNextMajor(from: "3.4.3")), 22 | ], 23 | targets: [ 24 | // Targets are the basic building blocks of a package, defining a module or a test suite. 25 | // Targets can depend on other targets in this package and products from dependencies. 26 | .target( 27 | name: "ProfileSwiftUI", dependencies: [ 28 | .product(name: "SwiftTraceD", package: "SwiftTrace"), 29 | .product(name: "DLKitCD", package: "DLKit"), "SwiftRegex"]), 30 | ] 31 | ) 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⏳Profile calls to SwiftUI 2 | 3 | ProfileSwiftUI gives you improved visibility of where CPU is being 4 | consumed inside your SwiftUI app. To use, add the ProfileSwiftUI 5 | Swift Package then import it and put something like the following 6 | in your RootView to setup logging then start polling statistics: 7 | 8 | ``` 9 | init() { 10 | ProfileSwiftUI.profile(interval: 10, top: 5) 11 | } 12 | ``` 13 | Output is rather verbose as it also logs calls SwiftUI makes 14 | internally to the "AttributeGraph" framework on which SwiftUI 15 | is based though these can be filtered out by passing a regex. 16 | (they will still appear in the periodic profile summary). The 17 | output is grouped by the function being called with detail 18 | entries breaking down where the function was called from. 19 | 20 | ## How it works. 21 | 22 | At the interface between your app and the SwiftUI framework, methods 23 | inside SwiftUI are dispatched indirectly through a form of lookup 24 | using a writable area of memory (this is the standard means by which 25 | the Darwin dynamic linker "binds" between frameworks). Using the 26 | [fishhook](https://github.com/facebook/fishhook) library is is 27 | possible to update this dispatch table by symbol name and "rebind" 28 | or "interpose" any implementation you would like of these functions. 29 | 30 | The [SwiftTrace](https://github.com/johnno1962/SwiftTrace) library 31 | allows you to generate a logging aspect (trampoline) around each 32 | function call which you can interpose these to take the place of the 33 | original call destination. To log calls to AttributeGraph a second 34 | set of interposes is made on the SwiftUI libray where it calls out. 35 | For whatever reason this second interpose only works in the simulator. 36 | -------------------------------------------------------------------------------- /Sources/ProfileSwiftUI/ProfileSwiftUI.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ProfileSwiftUI.swift 3 | // ProfileSwiftUI 4 | // 5 | // Created by John Holdsworth on 28/03/2024. 6 | // 7 | 8 | #if DEBUG || !SWIFT_PACKAGE 9 | #if canImport(Darwin) // Apple platforms only.. 10 | import Foundation 11 | #if SWIFT_PACKAGE 12 | import SwiftTraceD 13 | import SwiftRegex 14 | import DLKitCD 15 | #else 16 | import SwiftTrace 17 | #endif 18 | 19 | public struct ProfileSwiftUI { 20 | 21 | /** framework to intercept calls to*/ 22 | public static var packageFilter = "/SwiftUI.framework/" 23 | /** image number of framework to intercept calls to */ 24 | public static var targetImageNumber: UInt32 = 0 25 | /** Caller information extractor */ 26 | public static var relevantRegex = #"( closure #\d+|in \S+ : some|AG\w+)"# 27 | /** Regex pattern for methods to add profiling aspect */ 28 | public static var inclusions = NSRegularExpression(regexp: 29 | #"^AG| -> |body\.getter"#) 30 | /** demangled symbol names to avoid */ 31 | public static var exclusions = NSRegularExpression(regexp: 32 | #"descriptor|default argument|infix|subscript|-> (some|SwiftUI\.(Text|Font))|AGAttributeNil|callerTotals\.modify"#) 33 | 34 | /** format for function summary entries */ 35 | public static var entryFormat = "%10@\t🍿%@ 0x%llx" 36 | /** format for detail/caller entries */ 37 | public static var detailFormat = " ↳ %@\t%@" 38 | /** suffix for end of caller symbol */ 39 | public static var suffixFormat = " 0x%llx%s" 40 | /** formats for displaying elapsed times/counts */ 41 | public static var timeFormat = "%.3fms/%d" 42 | 43 | @discardableResult 44 | static func setTarget(framework: String) -> UInt32? { 45 | packageFilter = "/\(framework).framework/" 46 | guard let imageNumber = (UInt32(0)..<_dyld_image_count()).first(where: { 47 | strstr(_dyld_get_image_name($0), packageFilter) != nil }) else { return nil } 48 | targetImageNumber = imageNumber 49 | return targetImageNumber 50 | } 51 | 52 | static var tracer: STTracer = { existing, symname in 53 | var info = Dl_info() 54 | // Is the destinaton of the binding in the target image? 55 | guard existing >= autoBitCast(_dyld_get_image_header(ProfileSwiftUI.targetImageNumber)) && 56 | ProfileSwiftUI.targetImageNumber+1 < _dyld_image_count() && 57 | existing < autoBitCast(_dyld_get_image_header(ProfileSwiftUI.targetImageNumber+1)) || 58 | trie_dladdr(existing, &info) != 0 && strstr(info.dli_fname, 59 | ProfileSwiftUI.packageFilter) != nil else { return existing } 60 | let demangled = SwiftMeta.demangle(symbol: symname) ?? String(cString: symname)+"()" 61 | guard ProfileSwiftUI.inclusions.matches(demangled), 62 | !ProfileSwiftUI.exclusions.matches(demangled) else { 63 | return existing 64 | } 65 | // Construct logger aspect 66 | let tracer: UnsafeMutableRawPointer = autoBitCast(Profile(name: demangled, 67 | original: autoBitCast(existing))?.forwardingImplementation) 68 | // Continue logging after "injections" 69 | SwiftTrace.initialRebindings.append(rebinding(name: symname, 70 | replacement: tracer, replaced: nil)) 71 | return tracer 72 | } 73 | 74 | /// ProfileSwiftUI.profile() - log statistics on SwuiftUI log jams 75 | /// - Parameters: 76 | /// - interval: Interval between sumping stats. nil == manual polling. 77 | /// - top: # of functions to print stats for, 78 | /// - detail: # number of callers to break down sstats for. 79 | /// - reset: Whether to reset statistics between polls. 80 | /// - methodPattern: Additional app methods to incldue stats for. 81 | /// - traceFilter: Regex pattern for functions to log. Pass #"^(?!AG)"# to filter out AG 82 | public static func profile(interval: TimeInterval? = 10, top: Int = 10, 83 | detail: Int = 5, reset: Bool = true, 84 | methodPattern: String = #"\.getter"#, 85 | traceFilter: String? = nil) { 86 | SwiftTrace.startNewTrace(subLevels: 0) 87 | // Filter out messages? 88 | if let filter = traceFilter { 89 | SwiftTrace.traceFilterInclude = filter 90 | } 91 | // Includ elogging on all app methods matching pattern 92 | _ = SwiftTrace.interpose(aBundle: searchBundleImages(), methodName: methodPattern) 93 | 94 | guard let swiftUIImage = setTarget(framework: "SwiftUI") else { 95 | print("⏳ SwiftUI not in use.") 96 | return 97 | } 98 | print("⏳ Logging all calls from App into SwiftUI.") 99 | appBundleImages { path, header, slide in 100 | rebind_symbols_trace(autoBitCast(header), slide, tracer) 101 | } 102 | 103 | print("⏳ Logging all calls from SwiftUI into the AttributeGraph framework.") 104 | setTarget(framework: "AttributeGraph") 105 | rebind_symbols_trace(autoBitCast(_dyld_get_image_header(swiftUIImage)), 106 | _dyld_get_image_vmaddr_slide(swiftUIImage), 107 | tracer) 108 | 109 | _ = SwiftMeta.structsPassedByReference // perform ahead of time. 110 | // Start polling 111 | if interval != nil { 112 | pollStats(interval: interval, top: top, detail: detail, reset: reset) 113 | } 114 | } 115 | 116 | public static func pollStats(interval: TimeInterval? = 10, top: Int = 10, 117 | detail: Int = 5, reset: Bool = true) { 118 | DispatchQueue.main.asyncAfter(deadline: .now()+(interval ?? 0)) { 119 | print("\n⏳Profiles\n===========") 120 | func usecFormat(_ elapsed: TimeInterval, _ count: Int) -> String { 121 | return String(format: timeFormat, elapsed * 1000.0, count) 122 | } 123 | for (swizzle, elapsed, callerTotals, callerCounts) 124 | in sortedSwizzles(onlyFirst: top, reset: reset) { 125 | var total = 0, totals = [String: Double](), counts = [String: Int]() 126 | var info = Dl_info() 127 | for (caller, t) in callerTotals 128 | .sorted(by: { $0.value > $1.value } ) { 129 | guard trie_dladdr(caller, &info) != 0, let sym = info.dli_sname else { continue } 130 | let callerDecl = SwiftMeta.demangle(symbol: sym) ?? String(cString: sym) 131 | // print(callerDecl) 132 | var relevant: [String] = callerDecl[relevantRegex] 133 | if !relevant.isEmpty { 134 | relevant = relevant.suffix(1)+relevant.dropLast() 135 | } else { 136 | relevant = [callerDecl] 137 | } 138 | let key = relevant.joined() + 139 | String(format: suffixFormat, uintptr_t(bitPattern: info.dli_saddr), 140 | strrchr(info.dli_fname, Int32(UInt8(ascii: "/")))) 141 | totals[key, default: 0] += t 142 | let count = callerCounts[caller] ?? 0 143 | counts[key, default: 0] += count 144 | total += count 145 | } 146 | 147 | #if swift(>=5.10) 148 | totals = totals // Needed for Xcode 15.3! 149 | #endif 150 | print(String(format: entryFormat, usecFormat(elapsed, total), 151 | swizzle.signature, swizzle.implementation)) 152 | for (relevant, t) in totals 153 | .sorted(by: { $0.value > $1.value } ).prefix(detail) { 154 | print(String(format: detailFormat, 155 | usecFormat(t, counts[relevant] ?? 0), relevant)) 156 | } 157 | } 158 | 159 | if interval != nil { 160 | pollStats(interval: interval, top: top, detail: detail, reset: reset) 161 | } 162 | } 163 | } 164 | 165 | /** 166 | Sorted descending accumulated amount of time spent in each swizzled method. 167 | */ 168 | public static func sortedSwizzles(onlyFirst: Int? = nil, reset: Bool) -> 169 | [(SwiftTrace.Swizzle, TimeInterval, 170 | [UnsafeRawPointer: TimeInterval], [UnsafeRawPointer: Int])] { 171 | let sorted = SwiftTrace.lastSwiftTrace.activeSwizzles.map { $0.value } 172 | .sorted { $0.totalElapsed > $1.totalElapsed } 173 | let out = (onlyFirst != nil ? Array(sorted.prefix(onlyFirst!)) : sorted) 174 | .compactMap { $0 as? Profile }.map { 175 | return ($0, $0.totalElapsed, $0.callerTotals, $0.callerCounts) } 176 | if reset { 177 | for swizzle in sorted { 178 | swizzle.totalElapsed = 0 179 | guard let profile = swizzle as? Profile else { continue } 180 | profile.callerTotals.removeAll() 181 | profile.callerCounts.removeAll() 182 | } 183 | } 184 | return out 185 | } 186 | 187 | open class Profile: SwiftTrace.Decorated { 188 | 189 | open var callerCounts = [UnsafeRawPointer: Int]() 190 | open var callerTotals = [UnsafeRawPointer: TimeInterval]() 191 | 192 | open override func onExit(stack: inout SwiftTrace.ExitStack, 193 | invocation: SwiftTrace.Swizzle.Invocation) { 194 | callerTotals[invocation.returnAddress, default: 0] += invocation.elapsed 195 | callerCounts[invocation.returnAddress, default: 0] += 1 196 | super.onExit(stack: &stack, invocation: invocation) 197 | } 198 | } 199 | } 200 | 201 | extension Dl_info: CustomDebugStringConvertible { 202 | public var debugDescription: String { 203 | String(format: "0x%llx %@", uintptr_t(bitPattern: dli_saddr), 204 | SwiftMeta.demangle(symbol: dli_sname) ?? String(cString: dli_sname)) 205 | } 206 | } 207 | #endif 208 | #endif 209 | --------------------------------------------------------------------------------