In Linux, with C/C++ code, using gdb, how can you add a gdb breakpoint to scan the incoming strings in order to break on a particular string?
I don’t have access to a specific library’s code, but I want to break as soon as that library sends a specific string to standard out so I can go back up the stack and investigate the part of my code that is calling the library. Of course I don’t want to wait until a buffer flush occurs. Can this be done? Perhaps a routine in libstdc++ ?
This question might be a good starting point: how can I put a breakpoint on "something is printed to the terminal" in gdb?
So you could at least break whenever something is written to stdout. The method basically involves setting a breakpoint on the
writesyscall with a condition that the first argument is1(i.e. STDOUT). In the comments, there is also a hint as to how you could inspect the string parameter of thewritecall as well.x86 32-bit mode
I came up with the following and tested it with gdb 7.0.1-debian. It seems to work quite well.
$esp + 8contains a pointer to the memory location of the string passed towrite, so first you cast it to an integral, then to a pointer tochar.$esp + 4contains the file descriptor to write to (1 for STDOUT).x86 64-bit mode
If your process is running in x86-64 mode, then the parameters are passed through scratch registers
%rdiand%rsiNote that one level of indirection is removed since we’re using scratch registers rather than variables on the stack.
Variants
Functions other than
strcmpcan be used in the above snippets:strncmpis useful if you want match the firstnnumber of characters of the string being writtenstrstrcan be used to find matches within a string, since you can’t always be certain that the string you’re looking for is at the beginning of string being written through thewritefunction.Edit: I enjoyed this question and finding it’s subsequent answer. I decided to do a blog post about it.