Tuesday, March 1, 2016

How to Debug Remote using gdbserver

In this post, I will go through the method of debugging remotely using gdbserver. This is useful when you want to debug a program that constantly requires user's input. For example, consider the simple program test.c below:

#include <stdio.h>
int main (int argc, char** argv) {
    printf("input a positive number: ");
    int i;
    scanf ("%d", &i);
    for (; i>0; i--)
       printf("%d\n", i); 
return 0;

This program will require a user input and behave accordingly. Let's start debugging this remotely.

First, we need to compile it of course,
$ gcc -g test.c

Next, we need to install gdbserver
$ sudo apt-get install gdbserver -y

Let's run gdbserver and open up connection
$ gdbserver :1234 a.out 10
It should be waiting for connection to be made on port 1234. Don't forget the argument to the program, which is 10 in this case.

Now, we will open up another terminal and start gdb of a.out binary we just compiled
$ gdb -q

In the gdb prompt, run
(gdb) target remote :1234
(gdb) b test.c:7
(gdb) c

Now, you will see interactive gdb running on one of the terminal windows and the program running on the other!

No comments:

Post a Comment