Tuesday, September 13, 2016

How to Debug a Running Process Using GDB

Let's say you want to debug vim when run with sudo command, for example:
$ sudo vim /etc/fstab

It is easy to debug vim directly, but how would you do it when run with sudo? Well, here is one way to do it.

First, I will assume that you have vim executable file debug symbols. To find out how to compile vim with debug symbol, please refer to here. Say the file path is /usr/local/bin/vim.

Next, run the command that you want in one terminal:
$ sudo /usr/local/bin/vim /etc/fstab

Now, open up another terminal, and search for your vim process:
$ ps aux | grep vim
root     24687  0.0  0.0  63144  4212 pts/6    S+   19:04   0:00 sudo /usr/local/bin/vim /etc/fstab
root     24688  0.0  0.0  34180  5684 pts/6    S+   19:04   0:00 /usr/local/bin/vim /etc/fstab
linuxnme 24692  0.0  0.0  22572   988 pts/0    S+   19:04   0:00 grep --color=auto vim

We see two processes by root, one is sudo and the other is /usr/local/bin/vim, which is precisely what we want to debug, and its pid is 24668. To attach gdb to this process,
$ sudo gdb /usr/local/bin/vim 24688 -q
Reading symbols from /usr/local/bin/vim...done.
Attaching to program: /usr/local/bin/vim, process 24688
...
(gdb) 

Note that we are issuing sudo command before gdb here because we need superuser privilege to debug the process run by root.

Happy hacking!

No comments:

Post a Comment