Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift demangler
import Foundation
guard CommandLine.arguments.count > 1 else {
print("Please specify object file/executable")
exit(EXIT_FAILURE)
}
var nm = Process()
nm.launchPath = "/usr/bin/nm"
nm.arguments = [CommandLine.arguments[1]]
let pipe = Pipe()
nm.standardOutput = pipe.fileHandleForWriting
nm.launch()
pipe.fileHandleForWriting.closeFile()
let output = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)!
for line in output.components(separatedBy: "\n").dropLast() {
var line = line
if let symstart = line.lastIndex(of: " ") {
let symrange = line.index(symstart, offsetBy: 1) ..< line.endIndex
if let demangled = demangle(symbol: String(line[symrange])) {
line += " ==> " + demangled
}
}
print(line)
}
nm.waitUntilExit()
func demangle(symbol: String) -> String? {
return symbol.withCString { cString -> String? in
if let demangled = _stdlib_demangleImpl(cString,
mangledNameLength: UInt(strlen(cString)),
outputBuffer: nil, outputBufferSize: nil, flags: 0) ??
__cxa_demangle(cString+1, output_buffer: nil,
length: nil, status: nil) {
let out = String(cString: demangled)
free(demangled)
return out
}
return nil
}
}
@_silgen_name("swift_demangle")
privatefunc _stdlib_demangleImpl(_ mangledName: UnsafePointer<Int8>?, mangledNameLength: UInt, outputBuffer: UnsafeMutablePointer<Int8>?, outputBufferSize: UnsafeMutablePointer<UInt>?, flags: UInt32) -> UnsafeMutablePointer<Int8>?
@_silgen_name("__cxa_demangle")
func __cxa_demangle(_ mangled_name: UnsafePointer<Int8>?, output_buffer: UnsafePointer<Int8>?, length: UnsafeMutablePointer<size_t>?, status: UnsafeMutablePointer<Int32>?) -> UnsafeMutablePointer<Int8>?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment