From 7ea505e5bfd674f2d41879e107ee9a156f43582b Mon Sep 17 00:00:00 2001 From: George Barnett Date: Tue, 8 Jul 2025 11:18:42 +0100 Subject: [PATCH] Add dtrace parsing (#3288) Motivation: We often debug allocations on macOS, so being able to parse the output from malloc-aggregation.d is valuable. Modifications: - Add a dtrace parser to stackdiff Result: Can diff outputs from dtrace --- .../Sources/Stacks/Parsing/DTraceParser.swift | 137 ++++++++++++++++++ .../Sources/stackdiff/Stackdiff.swift | 2 +- .../Tests/StacksTests/DTraceParserTests.swift | 84 +++++++++++ 3 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 dev/stackdiff/Sources/Stacks/Parsing/DTraceParser.swift create mode 100644 dev/stackdiff/Tests/StacksTests/DTraceParserTests.swift diff --git a/dev/stackdiff/Sources/Stacks/Parsing/DTraceParser.swift b/dev/stackdiff/Sources/Stacks/Parsing/DTraceParser.swift new file mode 100644 index 000000000..3c6b2b52f --- /dev/null +++ b/dev/stackdiff/Sources/Stacks/Parsing/DTraceParser.swift @@ -0,0 +1,137 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation + +/// Parses output from NIO's `malloc-aggregation.d` DTrace script. +public struct DTraceParser: StackParser { + private static var allocationsRegex: Regex<(Substring, Substring)> { + /^ +(\d+)$/ + } + + private var state: ParseState + private var stacks: [WeightedStack] + + private init() { + self.stacks = [] + self.state = .parsingHeader + } + + private enum ParseResult { + case `continue` + case needsNextLine + case parsedStack(Stack, Int) + } + + private enum ParseState { + case parsingHeader + case parsingStack(ParsingStackState) + } + + private struct ParsingStackState { + var lines: [String] + + init() { + self.lines = [] + } + + mutating func parse(_ line: String) -> (ParseState, ParseResult) { + if let match = line.firstMatch(of: DTraceParser.allocationsRegex) { + if let count = Int(match.1) { + return (.parsingHeader, .parsedStack(Stack(self.lines), count)) + } else { + fatalError("Failed to convert '\(match.1)' to an Int") + } + } else { + let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) + let split = trimmed.split(separator: "+0x") + self.lines.append(split.first.map { String($0) } ?? trimmed) + return (.parsingStack(self), .needsNextLine) + } + } + } + + /// Parses input which looks roughly like the following: + /// + /// ``` + /// ===== + /// This will collect stack shots of allocations and print it when you exit dtrace. + /// So go ahead, run your tests and then press Ctrl+C in this window to see the aggregated result + /// ===== + /// 20896284696 + /// + /// libsystem_malloc.dylib`malloc_type_posix_memalign + /// libobjc.A.dylib`id2data(objc_object*, SyncKind, usage)+0x1a0 + /// libobjc.A.dylib`_objc_sync_enter_kind+0x1c + /// libobjc.A.dylib`initializeNonMetaClass+0xa8 + /// ... + /// libdispatch.dylib`_dispatch_client_callout+0x10 + /// libdispatch.dylib`_dispatch_once_callout+0x20 + /// libswiftCore.dylib`swift_getCanonicalPrespecializedGenericMetadata+0xc8 + /// libswiftCore.dylib`__swift_instantiateCanonicalPrespecializedGenericMetadata+0x28 + /// libswiftCore.dylib`_ContiguousArrayBuffer .init(_uninitializedCount:minimumCapacity:)+0x3c + /// do-some-allocs`specialized static do_some_allocs.main()+0x5c + /// do-some-allocs`do_some_allocs_main+0xc + /// 1 + /// + /// libsystem_malloc.dylib`malloc_type_posix_memalign + /// libobjc.A.dylib`id2data(objc_object*, SyncKind, usage)+0x1a0 + /// libobjc.A.dylib`_objc_sync_enter_kind+0x1c + /// ... + /// ``` + private mutating func parse(lines: some Sequence) -> [WeightedStack] { + for line in lines { + loop: while true { + switch self.parseNextState(line) { + case .parsedStack(let stack, let count): + self.stacks.append(WeightedStack(stack: stack, allocations: count)) + break loop + + case .continue: + () + + case .needsNextLine: + break loop + } + } + } + + return self.stacks + } + + private mutating func parseNextState(_ line: String) -> ParseResult { + switch self.state { + case .parsingHeader: + if line.hasPrefix(" ") { + // Loop around and parse the line as a stack. + self.state = .parsingStack(ParsingStackState()) + return .continue + } else { + return .needsNextLine + } + + case .parsingStack(var state): + let (state, result) = state.parse(line) + self.state = state + return result + } + } +} + +extension DTraceParser { + public static func parse(lines: some Sequence) -> [WeightedStack] { + var parser = Self() + return parser.parse(lines: lines) + } +} diff --git a/dev/stackdiff/Sources/stackdiff/Stackdiff.swift b/dev/stackdiff/Sources/stackdiff/Stackdiff.swift index 1eab46b08..052eeb767 100644 --- a/dev/stackdiff/Sources/stackdiff/Stackdiff.swift +++ b/dev/stackdiff/Sources/stackdiff/Stackdiff.swift @@ -70,7 +70,7 @@ extension AggregateStacks { case .heaptrack: stacks = HeaptrackParser.parse(lines: lines) case .dtrace: - fatalError("dtrace isn't supported yet, why don't you add it?") + stacks = DTraceParser.parse(lines: lines) case .bpftrace: fatalError("bpftrace isn't supported yet, why don't you add it?") } diff --git a/dev/stackdiff/Tests/StacksTests/DTraceParserTests.swift b/dev/stackdiff/Tests/StacksTests/DTraceParserTests.swift new file mode 100644 index 000000000..a41c7c79a --- /dev/null +++ b/dev/stackdiff/Tests/StacksTests/DTraceParserTests.swift @@ -0,0 +1,84 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Stacks +import Testing + +struct DTraceParserTests { + @Test + func parsing() throws { + // Real input but modified to be a lot shorter. + let input = """ + + ===== + This will collect stack shots of allocations and print it when you exit dtrace. + So go ahead, run your tests and then press Ctrl+C in this window to see the aggregated result + ===== + 20896284696 + + + libsystem_malloc.dylib`malloc_type_calloc + libobjc.A.dylib`class_createInstance+0x4c + libdispatch.dylib`_os_object_alloc_realized+0x20 + libdispatch.dylib`_dispatch_client_callout+0x10 + libdispatch.dylib`_dispatch_once_callout+0x20 + libswiftCore.dylib`swift_dynamicCast+0x60 + libswiftCore.dylib`_print_unlocked(_:_:)+0x2e4 + 13 + + libsystem_malloc.dylib`malloc_type_malloc + libswiftCore.dylib`swift_allocObject+0x88 + libswiftCore.dylib`_ContiguousArrayBuffer.init(_uninitializedCount:minimumCapacity:)+0xa0 + do-some-allocs`specialized static do_some_allocs.main()+0x5c + do-some-allocs`do_some_allocs_main+0xc + dyld`start+0x1870 + 10000 + + """ + + let lines = input.split(separator: "\n").map { String($0) } + let stacks = DTraceParser.parse(lines: lines) + + try #require(stacks.count == 2) + + let stack0 = stacks[0] + let expected0 = WeightedStack( + lines: [ + "libsystem_malloc.dylib`malloc_type_calloc", + "libobjc.A.dylib`class_createInstance", + "libdispatch.dylib`_os_object_alloc_realized", + "libdispatch.dylib`_dispatch_client_callout", + "libdispatch.dylib`_dispatch_once_callout", + "libswiftCore.dylib`swift_dynamicCast", + "libswiftCore.dylib`_print_unlocked(_:_:)", + ], + allocations: 13 + ) + #expect(stack0 == expected0) + + let stack1 = stacks[1] + let expected1 = WeightedStack( + lines: [ + "libsystem_malloc.dylib`malloc_type_malloc", + "libswiftCore.dylib`swift_allocObject", + "libswiftCore.dylib`_ContiguousArrayBuffer.init(_uninitializedCount:minimumCapacity:)", + "do-some-allocs`specialized static do_some_allocs.main()", + "do-some-allocs`do_some_allocs_main", + "dyld`start", + ], + allocations: 10000 + ) + #expect(stack1 == expected1) + } +}