-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathBacktrace.swift
677 lines (592 loc) · 22.7 KB
/
Backtrace.swift
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//===--- Backtrace.swift --------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 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 the `Backtrace` struct that represents a captured backtrace.
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import OS.Libc
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_implementationOnly import OS.Darwin
#endif
#if os(Linux)
@_implementationOnly import ImageFormats.Elf
#endif
/// Holds a backtrace.
public struct Backtrace: CustomStringConvertible, Sendable {
/// The type of an address.
///
/// This is intentionally _not_ a pointer, because you shouldn't be
/// dereferencing them; they may refer to some other process, for
/// example.
public typealias Address = UInt64
/// The unwind algorithm to use.
public enum UnwindAlgorithm {
/// Choose the most appropriate for the platform.
case auto
/// Use the fastest viable method.
///
/// Typically this means walking the frame pointers.
case fast
/// Use the most precise available method.
///
/// On Darwin and on ELF platforms, this will use EH unwind
/// information. On Windows, it will use Win32 API functions.
case precise
}
/// Represents an individual frame in a backtrace.
public enum Frame: CustomStringConvertible, Sendable {
/// A program counter value.
///
/// This might come from a signal handler, or an exception or some
/// other situation in which we have captured the actual program counter.
///
/// These can be directly symbolicated, as-is, with no adjustment.
case programCounter(Address)
/// A return address.
///
/// Corresponds to a normal function call.
///
/// Requires adjustment when symbolicating for a backtrace, because it
/// points at the address after the one that triggered the child frame.
case returnAddress(Address)
/// An async resume point.
///
/// Corresponds to an `await` in an async task.
///
/// Can be directly symbolicated, as-is.
case asyncResumePoint(Address)
/// Indicates a discontinuity in the backtrace.
///
/// This occurs when you set a limit and a minimum number of frames at
/// the top. For example, if you set a limit of 10 frames and a minimum
/// of 4 top frames, but the backtrace generated 100 frames, you will see
///
/// 0: frame 100 <----- bottom of call stack
/// 1: frame 99
/// 2: frame 98
/// 3: frame 97
/// 4: frame 96
/// 5: ... <----- omittedFrames(92)
/// 6: frame 3
/// 7: frame 2
/// 8: frame 1
/// 9: frame 0 <----- top of call stack
///
/// Note that the limit *includes* the discontinuity.
///
/// This is good for handling cases involving deep recursion.
case omittedFrames(Int)
/// Indicates a discontinuity of unknown length.
case truncated
/// The program counter, without any adjustment.
public var originalProgramCounter: Address {
switch self {
case let .returnAddress(addr):
return addr
case let .programCounter(addr):
return addr
case let .asyncResumePoint(addr):
return addr
case .omittedFrames(_), .truncated:
return 0
}
}
/// The adjusted program counter to use for symbolication.
public var adjustedProgramCounter: Address {
switch self {
case let .returnAddress(addr):
return addr - 1
case let .programCounter(addr):
return addr
case let .asyncResumePoint(addr):
return addr
case .omittedFrames(_), .truncated:
return 0
}
}
/// A textual description of this frame.
public func description(width: Int) -> String {
switch self {
case let .programCounter(addr):
return "\(hex(addr, width: width))"
case let .returnAddress(addr):
return "\(hex(addr, width: width)) [ra]"
case let .asyncResumePoint(addr):
return "\(hex(addr, width: width)) [async]"
case .omittedFrames(_), .truncated:
return "..."
}
}
/// A textual description of this frame.
public var description: String {
return description(width: MemoryLayout<Address>.size * 2)
}
}
/// Represents an image loaded in the process's address space
public struct Image: CustomStringConvertible, Sendable {
/// The name of the image (e.g. libswiftCore.dylib).
public var name: String
/// The full path to the image (e.g. /usr/lib/swift/libswiftCore.dylib).
public var path: String
/// The build ID of the image, as a byte array (note that the exact number
/// of bytes may vary, and that some images may not have a build ID).
public var buildID: [UInt8]?
/// The base address of the image.
public var baseAddress: Backtrace.Address
/// The end of the text segment in this image.
public var endOfText: Backtrace.Address
/// Provide a textual description of an Image.
public func description(width: Int) -> String {
if let buildID = self.buildID {
return "\(hex(baseAddress, width: width))-\(hex(endOfText, width: width)) \(hex(buildID)) \(name) \(path)"
} else {
return "\(hex(baseAddress, width: width))-\(hex(endOfText, width: width)) <no build ID> \(name) \(path)"
}
}
/// A textual description of an Image.
public var description: String {
return description(width: MemoryLayout<Address>.size * 2)
}
}
/// The architecture of the system that captured this backtrace.
public var architecture: String
/// The width of an address in this backtrace, in bits.
public var addressWidth: Int
/// A list of captured frame information.
public var frames: [Frame]
/// A list of captured images.
///
/// Some backtracing algorithms may require this information, in which case
/// it will be filled in by the `capture()` method. Other algorithms may
/// not, in which case it will be `nil` and you can capture an image list
/// separately yourself using `captureImages()`.
public var images: [Image]?
/// Holds information about the shared cache.
public struct SharedCacheInfo: Sendable {
/// The UUID from the shared cache.
public var uuid: [UInt8]
/// The base address of the shared cache.
public var baseAddress: Backtrace.Address
/// Says whether there is in fact a shared cache.
public var noCache: Bool
}
/// Information about the shared cache.
///
/// Holds information about the shared cache. On Darwin only, this is
/// required for symbolication. On non-Darwin platforms it will always
/// be `nil`.
public var sharedCacheInfo: SharedCacheInfo?
/// Format an address according to the addressWidth.
///
/// @param address The address to format.
/// @param prefix Whether to include a "0x" prefix.
///
/// @returns A String containing the formatted Address.
public func formatAddress(_ address: Address,
prefix: Bool = true) -> String {
return hex(address, prefix: prefix, width: (addressWidth + 3) / 4)
}
/// Capture a backtrace from the current program location.
///
/// The `capture()` method itself will not be included in the backtrace;
/// i.e. the first frame will be the one in which `capture()` was called,
/// and its programCounter value will be the return address for the
/// `capture()` method call.
///
/// @param algorithm Specifies which unwind mechanism to use. If this
/// is set to `.auto`, we will use the platform default.
/// @param limit The backtrace will include at most this number of
/// frames; you can set this to `nil` to remove the
/// limit completely if required.
/// @param offset Says how many frames to skip; this makes it easy to
/// wrap this API without having to inline things and
/// without including unnecessary frames in the backtrace.
/// @param top Sets the minimum number of frames to capture at the
/// top of the stack.
///
/// @returns A new `Backtrace` struct.
@inline(never)
@_semantics("use_frame_pointer")
public static func capture(algorithm: UnwindAlgorithm = .auto,
limit: Int? = 64,
offset: Int = 0,
top: Int = 16) throws -> Backtrace {
#if os(Linux)
let images = captureImages()
#else
let images: [Image]? = nil
#endif
// N.B. We use offset+1 here to skip this frame, rather than inlining
// this code into the client.
return try HostContext.withCurrentContext { ctx in
try capture(from: ctx,
using: UnsafeLocalMemoryReader(),
images: images,
algorithm: algorithm,
limit: limit,
offset: offset + 1,
top: top)
}
}
@_spi(Internal)
public static func capture<Ctx: Context, Rdr: MemoryReader>(
from context: Ctx,
using memoryReader: Rdr,
images: [Image]?,
algorithm: UnwindAlgorithm = .auto,
limit: Int? = 64,
offset: Int = 0,
top: Int = 16
) throws -> Backtrace {
let addressWidth = 8 * MemoryLayout<Ctx.Address>.size
switch algorithm {
// All of them, for now, use the frame pointer unwinder. In the long
// run, we should be using DWARF EH frame data for .precise.
case .auto, .fast, .precise:
let unwinder =
FramePointerUnwinder(context: context,
images: images,
memoryReader: memoryReader)
.dropFirst(offset)
if let limit = limit {
if limit <= 0 {
return Backtrace(architecture: context.architecture,
addressWidth: addressWidth,
frames: [.truncated])
}
let realTop = top < limit ? top : limit - 1
var iterator = unwinder.makeIterator()
var frames: [Frame] = []
// Capture frames normally until we hit limit
while let frame = iterator.next() {
if frames.count < limit {
frames.append(frame)
if frames.count == limit {
break
}
}
}
if realTop == 0 {
if let _ = iterator.next() {
// More frames than we were asked for; replace the last
// one with a discontinuity
frames[limit - 1] = .truncated
}
return Backtrace(architecture: context.architecture,
addressWidth: addressWidth,
frames: frames)
} else {
// If we still have frames at this point, start tracking the
// last `realTop` frames in a circular buffer.
if let frame = iterator.next() {
let topSection = limit - realTop
var topFrames: [Frame] = []
var topNdx = 0
var omittedFrames = 0
topFrames.reserveCapacity(realTop)
topFrames.insert(contentsOf: frames.suffix(realTop - 1), at: 0)
topFrames.append(frame)
while let frame = iterator.next() {
topFrames[topNdx] = frame
topNdx += 1
omittedFrames += 1
if topNdx >= realTop {
topNdx = 0
}
}
// Fix the backtrace to include a discontinuity followed by
// the contents of the circular buffer.
let firstPart = realTop - topNdx
let secondPart = topNdx
frames[topSection - 1] = .omittedFrames(omittedFrames)
frames.replaceSubrange(topSection..<(topSection+firstPart),
with: topFrames.suffix(firstPart))
frames.replaceSubrange((topSection+firstPart)..<limit,
with: topFrames.prefix(secondPart))
}
return Backtrace(architecture: context.architecture,
addressWidth: addressWidth,
frames: frames,
images: images)
}
} else {
return Backtrace(architecture: context.architecture,
addressWidth: addressWidth,
frames: Array(unwinder),
images: images)
}
}
}
/// Capture a list of the images currently mapped into the calling
/// process.
///
/// @returns A list of `Image`s.
public static func captureImages() -> [Image] {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
return captureImages(for: mach_task_self())
#else
return captureImages(using: UnsafeLocalMemoryReader())
#endif
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
private static func withDyldProcessInfo<T>(for task: task_t,
fn: (OpaquePointer?) throws -> T)
rethrows -> T {
var kret = kern_return_t(KERN_SUCCESS)
let dyldInfo = _dyld_process_info_create(task, 0, &kret)
if kret != KERN_SUCCESS {
fatalError("error: cannot create dyld process info")
}
defer {
_dyld_process_info_release(dyldInfo)
}
return try fn(dyldInfo)
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@_spi(Internal)
public static func captureImages(for process: Any) -> [Image] {
var images: [Image] = []
let task = process as! task_t
withDyldProcessInfo(for: task) { dyldInfo in
_dyld_process_info_for_each_image(dyldInfo) {
(machHeaderAddress, uuid, path) in
if let path = path, let uuid = uuid {
let pathString = String(cString: path)
let theUUID = Array(UnsafeBufferPointer(start: uuid,
count: MemoryLayout<uuid_t>.size))
let name: String
if let slashIndex = pathString.lastIndex(of: "/") {
name = String(pathString.suffix(from:
pathString.index(after:slashIndex)))
} else {
name = pathString
}
// Find the end of the __TEXT segment
var endOfText = machHeaderAddress + 4096
_dyld_process_info_for_each_segment(dyldInfo, machHeaderAddress) {
address, size, name in
if let name = String(validatingCString: name!), name == "__TEXT" {
endOfText = address + size
}
}
images.append(Image(name: name,
path: pathString,
buildID: theUUID,
baseAddress: Address(machHeaderAddress),
endOfText: Address(endOfText)))
}
}
}
return images.sorted(by: { $0.baseAddress < $1.baseAddress })
}
#else // !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS))
private struct AddressRange {
var low: Address = 0
var high: Address = 0
}
@_spi(Internal)
public static func captureImages<M: MemoryReader>(using reader: M,
forProcess pid: Int? = nil) -> [Image] {
var images: [Image] = []
#if os(Linux)
let path: String
if let pid = pid {
path = "/proc/\(pid)/maps"
} else {
path = "/proc/self/maps"
}
guard let procMaps = readString(from: path) else {
return []
}
// Find all the mapped files and get high/low ranges
var mappedFiles: [Substring:AddressRange] = [:]
for match in ProcMapsScanner(procMaps) {
let path = stripWhitespace(match.pathname)
if match.inode == "0" || path == "" {
continue
}
guard let start = Address(match.start, radix: 16),
let end = Address(match.end, radix: 16) else {
continue
}
if let range = mappedFiles[path] {
mappedFiles[path] = AddressRange(low: min(start, range.low),
high: max(end, range.high))
} else {
mappedFiles[path] = AddressRange(low: start,
high: end)
}
}
// Look for ELF headers in the process' memory
typealias Source = MemoryImageSource<M>
let source = Source(with: reader)
for match in ProcMapsScanner(procMaps) {
let path = stripWhitespace(match.pathname)
if match.inode == "0" || path == "" {
continue
}
guard let start = Address(match.start, radix: 16),
let end = Address(match.end, radix: 16),
let offset = Address(match.offset, radix: 16) else {
continue
}
if offset != 0 || end - start < EI_NIDENT {
continue
}
// Extract the filename from path
let name: Substring
if let slashIndex = path.lastIndex(of: "/") {
name = path.suffix(from: path.index(after: slashIndex))
} else {
name = path
}
// Inspect the image and extract the UUID and end of text
let range = mappedFiles[path]!
let subSource = SubImageSource(parent: source,
baseAddress: Source.Address(range.low),
length: Source.Size(range.high
- range.low))
var theUUID: [UInt8]? = nil
var endOfText: Address = range.low
if let image = try? Elf32Image(source: subSource) {
theUUID = image.uuid
for hdr in image.programHeaders {
if hdr.p_type == .PT_LOAD && (hdr.p_flags & PF_X) != 0 {
endOfText = max(endOfText, range.low + Address(hdr.p_vaddr
+ hdr.p_memsz))
}
}
} else if let image = try? Elf64Image(source: subSource) {
theUUID = image.uuid
for hdr in image.programHeaders {
if hdr.p_type == .PT_LOAD && (hdr.p_flags & PF_X) != 0 {
endOfText = max(endOfText, range.low + Address(hdr.p_vaddr
+ hdr.p_memsz))
}
}
} else {
// Not a valid ELF image
continue
}
let image = Image(name: String(name),
path: String(path),
buildID: theUUID,
baseAddress: range.low,
endOfText: endOfText)
images.append(image)
}
#endif
return images.sorted(by: { $0.baseAddress < $1.baseAddress })
}
#endif
/// Capture shared cache information.
///
/// @returns A `SharedCacheInfo`.
public static func captureSharedCacheInfo() -> SharedCacheInfo? {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
return captureSharedCacheInfo(for: mach_task_self())
#else
return nil
#endif
}
@_spi(Internal)
public static func captureSharedCacheInfo(for t: Any) -> SharedCacheInfo? {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
let task = t as! task_t
return withDyldProcessInfo(for: task) { dyldInfo in
var cacheInfo = dyld_process_cache_info()
_dyld_process_info_get_cache(dyldInfo, &cacheInfo)
let theUUID = withUnsafePointer(to: cacheInfo.cacheUUID) {
Array(UnsafeRawBufferPointer(start: $0,
count: MemoryLayout<uuid_t>.size))
}
return SharedCacheInfo(uuid: theUUID,
baseAddress: Address(cacheInfo.cacheBaseAddress),
noCache: cacheInfo.noCache)
}
#else // !os(Darwin)
return nil
#endif
}
/// Return a symbolicated version of the backtrace.
///
/// @param images Specifies the set of images to use for symbolication.
/// If `nil`, the function will look to see if the `Backtrace`
/// has already captured images. If it has, those will be
/// used; otherwise we will capture images at this point.
///
/// @param sharedCacheInfo Provides information about the location and
/// identity of the shared cache, if applicable.
///
/// @param showInlineFrames If `true` and we know how on the platform we're
/// running on, add virtual frames to show inline
/// function calls.
///
/// @param showSourceLocation If `true`, look up the source location for
/// each address.
///
/// @param useSymbolCache If the system we are on has a symbol cache,
/// says whether or not to use it.
///
/// @returns A new `SymbolicatedBacktrace`.
public func symbolicated(with images: [Image]? = nil,
sharedCacheInfo: SharedCacheInfo? = nil,
showInlineFrames: Bool = true,
showSourceLocations: Bool = true,
useSymbolCache: Bool = true)
-> SymbolicatedBacktrace? {
return SymbolicatedBacktrace.symbolicate(
backtrace: self,
images: images,
sharedCacheInfo: sharedCacheInfo,
showInlineFrames: showInlineFrames,
showSourceLocations: showSourceLocations,
useSymbolCache: useSymbolCache
)
}
/// Provide a textual version of the backtrace.
public var description: String {
var lines: [String] = []
let addressChars = (addressWidth + 3) / 4
var n = 0
for frame in frames {
lines.append("\(n)\t\(frame.description(width: addressChars))")
switch frame {
case let .omittedFrames(count):
n += count
default:
n += 1
}
}
if let images = images {
lines.append("")
lines.append("Images:")
lines.append("")
for (n, image) in images.enumerated() {
lines.append("\(n)\t\(image.description(width: addressChars))")
}
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
if let sharedCacheInfo = sharedCacheInfo {
lines.append("")
lines.append("Shared Cache:")
lines.append("")
lines.append(" UUID: \(hex(sharedCacheInfo.uuid))")
lines.append(" Base: \(hex(sharedCacheInfo.baseAddress, width: addressChars))")
lines.append(" Active: \(!sharedCacheInfo.noCache)")
}
#endif
return lines.joined(separator: "\n")
}
}