Use dtrace, lldb or gdb to find which file or line of code was responsible for a line of output in stdout or stderr?

357 Views Asked by At

I see a string being output to my Terminal, when I ran an executable. I have the source code (in C) of the executable, but it was not written by me. I compiled it with -g flag. Is there any way to know which line in which file resulted in the output, with dtrace, lldb, gdb, or any other means?

I am using macOS 10.13. When I ran gdb and the following: catch syscall write

I got this error: The feature 'catch syscall' is not supported on this architecture yet.

Is there any way that can achieve my goal?

1

There are 1 best solutions below

5
pmdj On

lldb tends to be better supported on macOS than gdb. You should be able to trace this call by using its conditional breakpoint feature.

While you can certainly trace the write() call with dtrace and get a stack trace using the ustack() action, I think you'll have a harder time pinpointing the state of the program than if you break on it in the debugger.

Your comment suggests you might be searching for a substring match. I suspect you can create a conditional breakpoint in lldb that matches a substring using something like this:

br s -n write -c 'strnstr((const char*)$rsi, "test", $rdx) != NULL'

I'm assuming lldb does not have argument names for the write function, so I'm using x86-64 calling convention register names directly. ($rdi = first argument, which would be the file descriptor; $rsi = second argument, buffer; $rdx = third argument, buffer length)