08. Using a debugger

Debugger
an instrument of dynamic analysis program execution path and memory usage
  • High-level: step-by-step C source execution and variable inspection
  • Low-level: assembler instructions execution and memory/register dump

Compiling for debug: cc -O0 -g program.c -o binaryprog

Debugging with gdb:

  1. Example program:
       1 #include <stdio.h>
       2 #define SIZE 10
       3 
       4 int A[SIZE] = {7,6,5,4,3,2,1,0,1,2};
       5 int B[SIZE];
       6 
       7 void fun(int *a, int *b, int len) {
       8         int i;
       9 
      10         for(i=0; i<len; i++)
      11                 b[i] = a[i];
      12 }
      13 
      14 int main(int argc, char *argv[]) {
      15         fun(A, B, 100500);
      16         return 0;
      17 }
    
  2. start with gdb binaryprog

  3. first set a breakpoint to main() function (it always exists in C program)

    (gdb) b main
    Breakpoint 1 at 0x400758: file arrr.c, line 15.
  4. run program until breakpoint is reached with r

    (gdb) r
    Starting program: /home/george/src/arrr
    Breakpoint 1, main (argc=1, argv=0x7fbf7854) at arrr.c:15
    15              fun(A, B, 100500);
  5. step into function call with s:

    (gdb) s
    fun (a=0x4108c0 <A>, b=0x410950 <B>, len=100500) at arrr.c:10
    10              for(i=0; i<len; i++)
  6. run next c code (executing function call as one instruction) with n

    (gdb) n
    11                      b[i] = a[i];
    (gdb) n
    10              for(i=0; i<len; i++)
    (gdb)
    11                      b[i] = a[i];
    (gdb)
    10              for(i=0; i<len; i++)
    (gdb)
    11                      b[i] = a[i];
    • Also you can just press enter for repeating last command
  7. print a variable with p

    (gdb) p a
    $1 = (int *) 0x4108c0 <A>
    (gdb) p B
    $2 = {7, 6, 0, 0, 0, 0, 0, 0, 0, 0}
    (gdb) p i
    $3 = 2
    • ($1, $2 etc. is the number of expressions printed)

  8. Add an expression to display list to display it on all command with display:

    (gdb) display i
    1: i = 2
    (gdb) n
    10              for(i=0; i<len; i++)
    1: i = 2
    (gdb)
    11                      b[i] = a[i];
    1: i = 3
    (gdb)
    10              for(i=0; i<len; i++)
    1: i = 3
  9. quit with q
    (gdb) q
    A debugging session is active.
    
            Inferior 1 [process 10578] will be killed.
    
    Quit anyway? (y or n) y

Using breakpoints

GDB documentation

Other debuggers

On sugon:

On local machine (linux):

H/W

Pick up your favorite debugger and learn how to use it

HSE/ProgrammingOS/Lab_08_UsingDebugger (последним исправлял пользователь FrBrGeorge 2020-05-04 12:10:36)