1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
|
//===--- TargetLinux.swift - Represents a process we are inspecting -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Defines `Target`, which represents the process we are inspecting.
// This is the Linux version.
//
//===----------------------------------------------------------------------===//
#if os(Linux)
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif
import _Backtracing
@_spi(Internal) import _Backtracing
@_spi(Contexts) import _Backtracing
@_spi(MemoryReaders) import _Backtracing
@_spi(Utils) import _Backtracing
@_implementationOnly import Runtime
enum SomeBacktrace {
case raw(Backtrace)
case symbolicated(SymbolicatedBacktrace)
}
struct TargetThread {
typealias ThreadID = pid_t
var id: ThreadID
var context: HostContext?
var name: String
var backtrace: SomeBacktrace
}
class Target {
typealias Address = UInt64
var pid: pid_t
var name: String
var signal: UInt64
var faultAddress: Address
var crashingThread: TargetThread.ThreadID
var images: [Backtrace.Image] = []
var threads: [TargetThread] = []
var crashingThreadNdx: Int = -1
var signalName: String {
switch signal {
case UInt64(SIGQUIT): return "SIGQUIT"
case UInt64(SIGABRT): return "SIGABRT"
case UInt64(SIGBUS): return "SIGBUS"
case UInt64(SIGFPE): return "SIGFPE"
case UInt64(SIGILL): return "SIGILL"
case UInt64(SIGSEGV): return "SIGSEGV"
case UInt64(SIGTRAP): return "SIGTRAP"
default: return "\(signal)"
}
}
var signalDescription: String {
switch signal {
case UInt64(SIGQUIT): return "Terminated"
case UInt64(SIGABRT): return "Aborted"
case UInt64(SIGBUS): return "Bus error"
case UInt64(SIGFPE): return "Floating point exception"
case UInt64(SIGILL): return "Illegal instruction"
case UInt64(SIGSEGV): return "Bad pointer dereference"
case UInt64(SIGTRAP): return "System trap"
default:
return "Signal \(signal)"
}
}
var reader: CachingMemoryReader<MemserverMemoryReader>
// Get the name of a process
private static func getProcessName(pid: pid_t) -> String {
let path = "/proc/\(pid)/comm"
guard let name = readString(from: path) else {
return ""
}
return String(stripWhitespace(name))
}
/// Get the name of a thread
private func getThreadName(tid: Int64) -> String {
let path = "/proc/\(pid)/task/\(tid)/comm"
guard let name = readString(from: path) else {
return ""
}
let trimmed = String(stripWhitespace(name))
// Allow the main thread to use the process' name, but other
// threads will have an empty name unless they've set the name
// explicitly
if trimmed == self.name && pid != tid {
return ""
}
return trimmed
}
init(crashInfoAddr: UInt64, limit: Int?, top: Int, cache: Bool,
symbolicate: SwiftBacktrace.Symbolication) {
// fd #4 is reserved for the memory server
let memserverFd: CInt = 4
pid = getppid()
reader = CachingMemoryReader(for: MemserverMemoryReader(fd: memserverFd))
name = Self.getProcessName(pid: pid)
let crashInfo: CrashInfo
do {
crashInfo = try reader.fetch(from: crashInfoAddr, as: CrashInfo.self)
} catch {
print("swift-backtrace: unable to fetch crash info.")
exit(1)
}
crashingThread = TargetThread.ThreadID(crashInfo.crashing_thread)
signal = crashInfo.signal
faultAddress = crashInfo.fault_address
images = Backtrace.captureImages(using: reader,
forProcess: Int(pid))
do {
try fetchThreads(threadListHead: Address(crashInfo.thread_list),
limit: limit, top: top, cache: cache,
symbolicate: symbolicate)
} catch {
print("swift-backtrace: failed to fetch thread information: \(error)")
exit(1)
}
}
/// Fetch information about all of the process's threads; the crash_info
/// structure contains a linked list of thread ucontexts, which may not
/// include every thread. In particular, if a thread was stuck in an
/// uninterruptible wait, we won't have a ucontext for it.
func fetchThreads(
threadListHead: Address,
limit: Int?, top: Int, cache: Bool,
symbolicate: SwiftBacktrace.Symbolication
) throws {
var next = threadListHead
while next != 0 {
let t = try reader.fetch(from: next, as: thread.self)
next = t.next
guard let ucontext
= try? reader.fetch(from: t.uctx, as: ucontext_t.self) else {
// This can happen if a thread is in an uninterruptible wait
continue
}
let context = HostContext.fromHostMContext(ucontext.uc_mcontext)
let backtrace = try Backtrace.capture(from: context,
using: reader,
images: images,
limit: limit,
top: top)
let shouldSymbolicate: Bool
let showInlineFrames: Bool
let showSourceLocations: Bool
switch symbolicate {
case .off:
shouldSymbolicate = false
showInlineFrames = false
showSourceLocations = false
case .fast:
shouldSymbolicate = true
showInlineFrames = false
showSourceLocations = false
case .full:
shouldSymbolicate = true
showInlineFrames = true
showSourceLocations = true
}
if shouldSymbolicate {
guard let symbolicated
= backtrace.symbolicated(with: images,
sharedCacheInfo: nil,
showInlineFrames: showInlineFrames,
showSourceLocations: showSourceLocations,
useSymbolCache: cache) else {
print("unable to symbolicate backtrace for thread \(t.tid)")
exit(1)
}
threads.append(TargetThread(id: TargetThread.ThreadID(t.tid),
context: context,
name: getThreadName(tid: t.tid),
backtrace: .symbolicated(symbolicated)))
} else {
threads.append(TargetThread(id: TargetThread.ThreadID(t.tid),
context: context,
name: getThreadName(tid: t.tid),
backtrace: .raw(backtrace)))
}
}
// Sort the threads by thread ID; the main thread always sorts
// lower than any other.
threads.sort {
return $0.id == pid || ($1.id != pid && $0.id < $1.id)
}
// Find the crashing thread index
if let ndx = threads.firstIndex(where: { $0.id == crashingThread }) {
crashingThreadNdx = ndx
} else {
print("unable to find the crashing thread")
exit(1)
}
}
func redoBacktraces(
limit: Int?, top: Int, cache: Bool,
symbolicate: SwiftBacktrace.Symbolication
) {
for (ndx, thread) in threads.enumerated() {
guard let context = thread.context else {
continue
}
guard let backtrace = try? Backtrace.capture(from: context,
using: reader,
images: images,
limit: limit,
top: top) else {
print("unable to capture backtrace from context for thread \(ndx)")
continue
}
let shouldSymbolicate: Bool
let showInlineFrames: Bool
let showSourceLocations: Bool
switch symbolicate {
case .off:
shouldSymbolicate = false
showInlineFrames = false
showSourceLocations = false
case .fast:
shouldSymbolicate = true
showInlineFrames = false
showSourceLocations = false
case .full:
shouldSymbolicate = true
showInlineFrames = true
showSourceLocations = true
}
if shouldSymbolicate {
guard let symbolicated = backtrace.symbolicated(
with: images,
sharedCacheInfo: nil,
showInlineFrames: showInlineFrames,
showSourceLocations: showSourceLocations,
useSymbolCache: cache) else {
print("unable to symbolicate backtrace from context for thread \(ndx)")
continue
}
threads[ndx].backtrace = .symbolicated(symbolicated)
} else {
threads[ndx].backtrace = .raw(backtrace)
}
}
}
func withDebugger(_ body: () -> ()) throws {
print("""
From another shell, please run
lldb --attach-pid \(pid) -o c
""")
body()
}
}
#endif // os(Linux)
|