Skip to content

Commit bfead15

Browse files
authored
Merge pull request #3165 from compnerd/thread-symbols
Foundation: correct invalid memory usage in `callStackSymbols`
2 parents 7ff8436 + 3e1459d commit bfead15

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

Sources/Foundation/Thread.swift

+18-15
Original file line numberDiff line numberDiff line change
@@ -391,26 +391,29 @@ open class Thread : NSObject {
391391
return backtraceAddresses { (addresses, count) in
392392
var symbols: [String] = []
393393

394-
var buffer: UnsafeMutablePointer<Int8> =
395-
UnsafeMutablePointer<Int8>
396-
.allocate(capacity: MemoryLayout<SYMBOL_INFO>.size + 128)
394+
let buffer: UnsafeMutablePointer<UInt8> =
395+
.allocate(capacity: MemoryLayout<SYMBOL_INFO>.size + 128)
397396
defer { buffer.deallocate() }
398397

399-
buffer.withMemoryRebound(to: SYMBOL_INFO.self, capacity: 1) {
400-
$0.pointee.SizeOfStruct = ULONG(MemoryLayout<SYMBOL_INFO>.size)
401-
$0.pointee.MaxNameLen = 128
402-
403-
var address = addresses
404-
for _ in 1...count {
405-
var dwDisplacement: DWORD64 = 0
406-
if !SymFromAddr(hProcess, unsafeBitCast(address.pointee, to: DWORD64.self), &dwDisplacement, $0) {
407-
symbols.append("\($0.pointee)")
408-
} else {
409-
symbols.append(String(cString: &$0.pointee.Name))
398+
let pSymbolInfo =
399+
UnsafeMutableRawPointer(buffer).assumingMemoryBound(to: SYMBOL_INFO.self)
400+
pSymbolInfo.pointee.SizeOfStruct = ULONG(MemoryLayout<SYMBOL_INFO>.size)
401+
pSymbolInfo.pointee.MaxNameLen = 128
402+
403+
let addresses: UnsafeMutableBufferPointer<PVOID?> =
404+
UnsafeMutableBufferPointer<PVOID?>(start: addresses, count: count)
405+
for address in addresses {
406+
var dwDisplacement: DWORD64 = 0
407+
if SymFromAddr(hProcess, DWORD64(UInt(bitPattern: address)),
408+
&dwDisplacement, pSymbolInfo) {
409+
withUnsafePointer(to: pSymbolInfo.pointee.Name) {
410+
symbols.append(String(cString: $0))
410411
}
411-
address = address.successor()
412+
} else {
413+
symbols.append("\(pSymbolInfo.pointee)")
412414
}
413415
}
416+
414417
return symbols
415418
}
416419
#else

0 commit comments

Comments
 (0)