使用 DTrace 在 Rust 上获取堆栈跟踪/分析数据

Using DTrace to get stack traces / profiling data on Rust

我正在尝试获取我的 Rust 代码的漂亮火焰图。不幸的是,Xcode 8.3 不再支持导出分析数据,所以我一直在尝试使用 DTrace 来获取分析数据。

我在 Cargo.toml 中为发布二进制文件启用了调试信息:

[profile.release]
debug = true

然后我 运行 发布二进制文件 (mybinaryname),并使用 DTrace 对堆栈跟踪进行采样:

sudo dtrace -n 'profile-997 /execname == "mybinaryname"/ { @[ustack(100)] = count(); }' -o out.user_stacks

最终结果是这样的:

          0x10e960500
          0x10e964632
          0x10e9659e0
          0x10e937edd
          0x10e92aae2
          0x10e92d0d7
          0x10e982c8b
          0x10e981fc1
          0x7fff93c70235
          0x1
            1

为了比较,获取 iTerm2 的痕迹让我得到了像这样的漂亮痕迹:

          CoreFoundation`-[__NSArrayM removeAllObjects]
          AppKit`_NSGestureRecognizerUpdate+0x769
          CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__+0x17
          CoreFoundation`__CFRunLoopDoObservers+0x187
          CoreFoundation`__CFRunLoopRun+0x4be
          CoreFoundation`CFRunLoopRunSpecific+0x1a4
          HIToolbox`RunCurrentEventLoopInMode+0xf0
          HIToolbox`ReceiveNextEventCommon+0x1b0
          HIToolbox`_BlockUntilNextEventMatchingListInModeWithFilter+0x47
          AppKit`_DPSNextEvent+0x460
          AppKit`-[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:]+0xaec
          AppKit`-[NSApplication run]+0x39e
          AppKit`NSApplicationMain+0x4d5
          iTerm2`main+0x6e
          libdyld.dylib`start+0x1
          iTerm2`0x1
            1

是否可以在 Rust 代码中获取带有调试信息的堆栈跟踪? (Xcode 的 Instruments 肯定可以看到函数名称,所以它们就在那里!)如果可能的话,我是否需要采取一些额外的步骤,或者我只是做错了什么?

我找到了一个解决方法并了解了为什么它可能不起作用,但原因不是 100% 清楚。

rustc 生成的调试符号可以在 target/release/deps/mybinaryname-hashcode.dSYM 中找到。在同一目录中有一个二进制文件target/release/deps/mybinaryname-hashcode,符号对应。

MacOS 上的调试符号查找库非常神奇 – mentioned in the LLDB docs,可以使用各种方法找到符号,包括 Spotlight 搜索。我什至不确定 Xcode 的仪器和捆绑的 DTrace 使用的是哪些框架。 (提到了名为 DebugSymbols.framework 和 CoreSymbolication.framework 的框架。)因为这个魔法,我放弃了试图理解 为什么 不起作用。

解决方法是传递 dtrace -p 选项以及被检查进程的 PID:

sudo dtrace -p $PID -n 'profile-997 /pid == '$PID'/ { @[ustack(100)] = count(); }' -o $TMPFILE &>/dev/null

这是 -pman

Grab the specified process-ID pid, cache its symbol tables, and exit upon its completion. If more than one -p option is present on the command line, dtrace exits when all commands have exited, reporting the exit status for each process as it terminates. The first process-ID is made available to any D programs specified on the command line or using the -s option through the $target macro variable.

不清楚为什么默认显示其他各种二进制文件的调试信息,或者为什么 Rust 二进制文件需要 -p 选项,但它作为一种解决方法发挥了作用。