|
| 1 | +// |
| 2 | +// This source file is part of the Swift.org open source project |
| 3 | +// |
| 4 | +// Copyright (c) 2024 Apple Inc. and the Swift project authors |
| 5 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | +// |
| 7 | +// See https://swift.org/LICENSE.txt for license information |
| 8 | +// See https://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | +// |
| 10 | + |
| 11 | +private import _TestingInternals |
| 12 | + |
| 13 | +/// A type representing a backtrace or stack trace. |
| 14 | +@_spi(ForToolsIntegrationOnly) |
| 15 | +extension Backtrace { |
| 16 | + /// Demangle a symbol name. |
| 17 | + /// |
| 18 | + /// - Parameters: |
| 19 | + /// - mangledSymbolName: The symbol name to demangle. |
| 20 | + /// |
| 21 | + /// - Returns: The demangled form of `mangledSymbolName` according to the |
| 22 | + /// Swift standard library or the platform's C++ standard library, or `nil` |
| 23 | + /// if the symbol name could not be demangled. |
| 24 | + private static func _demangle(_ mangledSymbolName: String) -> String? { |
| 25 | + guard let demangledSymbolName = swt_copyDemangledSymbolName(mangledSymbolName) else { |
| 26 | + return nil |
| 27 | + } |
| 28 | + defer { |
| 29 | + free(demangledSymbolName) |
| 30 | + } |
| 31 | + return String(validatingCString: demangledSymbolName) |
| 32 | + } |
| 33 | + |
| 34 | + /// Symbolicate a sequence of addresses. |
| 35 | + /// |
| 36 | + /// - Parameters: |
| 37 | + /// - addresses: The sequence of addresses. These addresses must have |
| 38 | + /// originated in the current process. |
| 39 | + /// - mode: How to symbolicate the addresses in the backtrace. |
| 40 | + /// |
| 41 | + /// - Returns: An array of strings representing the names of symbols in |
| 42 | + /// `addresses`. |
| 43 | + /// |
| 44 | + /// If an address in `addresses` cannot be symbolicated, it is converted to a |
| 45 | + /// string using ``Swift/String/init(describingForTest:)``. |
| 46 | + private static func _symbolicate(addresses: UnsafeBufferPointer<UnsafeRawPointer?>, mode: SymbolicationMode) -> [String] { |
| 47 | + let count = addresses.count |
| 48 | + var symbolNames = [(String, displacement: UInt)?](repeating: nil, count: count) |
| 49 | + |
| 50 | +#if SWT_TARGET_OS_APPLE |
| 51 | + for (i, address) in addresses.enumerated() { |
| 52 | + guard let address else { |
| 53 | + continue |
| 54 | + } |
| 55 | + var info = Dl_info() |
| 56 | + if 0 != dladdr(address, &info) { |
| 57 | + let displacement = UInt(bitPattern: address) - UInt(bitPattern: info.dli_saddr) |
| 58 | + if var symbolName = info.dli_sname.flatMap(String.init(validatingCString:)) { |
| 59 | + if mode != .mangled { |
| 60 | + symbolName = _demangle(symbolName) ?? symbolName |
| 61 | + } |
| 62 | + symbolNames[i] = (symbolName, displacement) |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +#elseif os(Linux) |
| 67 | + // Although Linux has dladdr(), it does not have symbol names from ELF |
| 68 | + // binaries by default. The standard library's backtracing functionality has |
| 69 | + // implemented sufficient ELF/DWARF parsing to be able to symbolicate Linux |
| 70 | + // backtraces. TODO: adopt the standard library's Backtrace on Linux |
| 71 | + // Note that this means on Linux we don't have demangling capability (since |
| 72 | + // we don't have the mangled symbol names in the first place) so this code |
| 73 | + // does not check the mode argument. |
| 74 | +#elseif os(Windows) |
| 75 | + _withDbgHelpLibrary { hProcess in |
| 76 | + guard let hProcess else { |
| 77 | + return |
| 78 | + } |
| 79 | + for (i, address) in addresses.enumerated() { |
| 80 | + guard let address else { |
| 81 | + continue |
| 82 | + } |
| 83 | + |
| 84 | + withUnsafeTemporaryAllocation(of: SYMBOL_INFO_PACKAGEW.self, capacity: 1) { symbolInfo in |
| 85 | + let symbolInfo = symbolInfo.baseAddress! |
| 86 | + symbolInfo.pointee.si.SizeOfStruct = ULONG(MemoryLayout<SYMBOL_INFOW>.stride) |
| 87 | + symbolInfo.pointee.si.MaxNameLen = ULONG(MAX_SYM_NAME) |
| 88 | + var displacement = DWORD64(0) |
| 89 | + if SymFromAddrW(hProcess, DWORD64(clamping: UInt(bitPattern: address)), &displacement, symbolInfo.pointer(to: \.si)!), |
| 90 | + var symbolName = String.decodeCString(symbolInfo.pointer(to: \.si.Name)!, as: UTF16.self)?.result { |
| 91 | + if mode != .mangled { |
| 92 | + symbolName = _demangle(symbolName) ?? symbolName |
| 93 | + } |
| 94 | + symbolNames[i] = (symbolName, UInt(clamping: displacement)) |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | +#elseif os(WASI) |
| 100 | + // WASI does not currently support backtracing let alone symbolication. |
| 101 | +#else |
| 102 | +#warning("Platform-specific implementation missing: backtrace symbolication unavailable") |
| 103 | +#endif |
| 104 | + |
| 105 | + var result = [String]() |
| 106 | + result.reserveCapacity(count) |
| 107 | + for (i, address) in addresses.enumerated() { |
| 108 | + let formatted = if let (symbolName, displacement) = symbolNames[i] { |
| 109 | + if mode == .preciseDemangled { |
| 110 | + "\(i) \(symbolName) (\(String(describingForTest: address))+\(displacement))" |
| 111 | + } else { |
| 112 | + symbolName |
| 113 | + } |
| 114 | + } else { |
| 115 | + String(describingForTest: address) |
| 116 | + } |
| 117 | + result.append(formatted) |
| 118 | + } |
| 119 | + return result |
| 120 | + } |
| 121 | + |
| 122 | + /// An enumeration describing the symbolication mode to use when handling |
| 123 | + /// events containing backtraces. |
| 124 | + public enum SymbolicationMode: Sendable { |
| 125 | + /// The backtrace should be symbolicated, but no demangling should be |
| 126 | + /// performed. |
| 127 | + case mangled |
| 128 | + |
| 129 | + /// The backtrace should be symbolicated and Swift and C++ symbols should be |
| 130 | + /// demangled if possible. |
| 131 | + case demangled |
| 132 | + |
| 133 | + /// The backtrace should be symbolicated, Swift and C++ symbols should be |
| 134 | + /// demangled if possible, and precise symbol addresses and offsets should |
| 135 | + /// be provided if available. |
| 136 | + case preciseDemangled |
| 137 | + } |
| 138 | + |
| 139 | + /// Symbolicate the addresses in this backtrace. |
| 140 | + /// |
| 141 | + /// - Parameters: |
| 142 | + /// - mode: How to symbolicate the addresses in the backtrace. |
| 143 | + /// |
| 144 | + /// - Returns: An array of strings representing the names of symbols in |
| 145 | + /// `addresses`. |
| 146 | + /// |
| 147 | + /// If an address in `addresses` cannot be symbolicated, it is converted to a |
| 148 | + /// string using ``Swift/String/init(describingForTest:)``. |
| 149 | + public func symbolicate(_ mode: SymbolicationMode) -> [String] { |
| 150 | +#if _pointerBitWidth(_64) |
| 151 | + // The width of a pointer equals the width of an `Address`, so we can just |
| 152 | + // bitcast the memory rather than mapping through UInt first. |
| 153 | + addresses.withUnsafeBufferPointer { addresses in |
| 154 | + addresses.withMemoryRebound(to: UnsafeRawPointer?.self) { addresses in |
| 155 | + Self._symbolicate(addresses: addresses, mode: mode) |
| 156 | + } |
| 157 | + } |
| 158 | +#else |
| 159 | + let addresses = addresses.map { UnsafeRawPointer(bitPattern: UInt($0)) } |
| 160 | + return addresses.withUnsafeBufferPointer { addresses in |
| 161 | + Self._symbolicate(addresses: addresses, mode: mode) |
| 162 | + } |
| 163 | +#endif |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +#if os(Windows) |
| 168 | +// MARK: - |
| 169 | + |
| 170 | +/// Configure the environment to allow calling into the Debug Help library. |
| 171 | +/// |
| 172 | +/// - Parameters: |
| 173 | +/// - body: A function to invoke. A process handle valid for use with Debug |
| 174 | +/// Help functions is passed in, or `nullptr` if the Debug Help library |
| 175 | +/// could not be initialized. |
| 176 | +/// - context: An arbitrary pointer to pass to `body`. |
| 177 | +/// |
| 178 | +/// On Windows, the Debug Help library (DbgHelp.lib) is not thread-safe. All |
| 179 | +/// calls into it from the Swift runtime and stdlib should route through this |
| 180 | +/// function. |
| 181 | +private func _withDbgHelpLibrary(_ body: (HANDLE?) -> Void) { |
| 182 | + withoutActuallyEscaping(body) { body in |
| 183 | + withUnsafePointer(to: body) { context in |
| 184 | + _swift_win32_withDbgHelpLibrary({ hProcess, context in |
| 185 | + let body = context!.load(as: ((HANDLE?) -> Void).self) |
| 186 | + body(hProcess) |
| 187 | + }, .init(mutating: context)) |
| 188 | + } |
| 189 | + } |
| 190 | +} |
| 191 | +#endif |
0 commit comments