Recently, part of the test suite I was working on was getting stuck in some test. Unfortunately I wasn’t able to find out where or why from the logs. To make things harder I could not find the right spot to place the debugger either. To sum up, I was totally stuck.
Finally I read a nice article about using GDB to inspect a running Ruby process. I thought it would be a piece of cake to get it working. But it turned out to be quite an effort to make the GDB and Ruby to play it nice. Here is the story…
First attempt was quite successful:
OK. So the debugger “works”. It successfully attaches to the process. Debugging symbols “are there” (sort of). So why is not working?
My Ruby was compiled with
-O3 flag so probably is missing some
information gdb needs to get the return types of functions.
The next step was to find out these types so I could write them by hand. I found The Ruby Cross Reference site which does great a job annotating Ruby source code with links and meanings.
You can just search for type identifier (type, function, whatever) and it will
point you at the definition in header files. For example the
has a return type
VALUE. Hmm. Using
VALUE as type does not work in gdb,
probably because of optimization. So clicking
VALUE reveals that it
is defined as
unsigned long or
uintptr_t. On OS X gdb does not know about
uintptr_t so, by elimination, it is
unsigned long. The final version of the gdb macro
looks like this:
Armed with this knowledge I was able to annotate some gdb_macros_for_ruby with type information and use them to get stack traces and variables.
If you want to have ruby with debugging symbols you have to compile it.
rvm_configure_env=(CFLAGS=-O3) in my
.rvmrc so all rubies are
compiled with a high optimization level. Unfortunately such optimization
conflicts with flags we want to pass to rvm. As a workaround you can do:
Using GDB with Ruby compiled this way is much easier because you don’t have to specify the return types and get them for free even with source code. It is useful to learn how to annotate gdb macros with return types in case you don’t want or can’t compile own Ruby, but it is not mandatory.
The first GDB I tried was GDB 7.5.1 installed via homebrew from homebrew-dupes.
rb_ call I tried to do failed miserably with:
Unfortunately I wasn’t able to find out why this happened or how to work around it. If you know why this is happening please leave a comment, it would be awesome to know why.
In our CI (Continuous integration) build we had some processes that from time to time got stuck. But thanks to GDB we have the tools to know what is going on.
And what is really cool is that when you have
pry, you can spawn new Pry
session from the gdb like:
Together with pry-stack_explorer you should be able to get anywhere in
the stack and inspect things. Then just
exit the pry and continue.