Saturday, October 23, 2010

Debugging with GDB's Cheat-Sheet of Commonly Used Options

Gdb:
Compiling a program for debugging:
    g++ -ggdb -O0 hello.cpp   # 
    g++ -g3 -O0 hello.cpp       # -g3 compiles debugging info for preprocessor macros and no optimization

Running a program under the debugger without arguments
$> gdb myProgram

Setting the program arguments:
   a)  $> gdb --args myProgram  10 20 30 40
   b)  (gdb) start 10 20 30 40  # sets temporary breakpoint at main() and calls run.
   c)  (gdb) file myProgram
        (gdb) run 10 20 30 40
   d)   (gdb)  set args 10 20 30 40
         (gdb) show args
        (gdb) run
    e) $> gdb myProgram core
    f) $> gdb -tui myProgram core  # start vim/emacs ide for debug session
Redirect input/output of debugged program (inferior process):
    (gdb) file myProgram
    (gdb) run  < input.txt > myProgram.log

    #Start debug session by Running a wrapper program to setup the environment for the debugged executable:
    (gdb) set exec-wrapper env 'LD_PRELOAD=libtest.so'
    (gdb) run

Quitting gdb:
    a)  quit
    b) Ctrl-d
Displaying source code:
    list    #  displays 10 lines from current point in source code
    list    #   displays 10 lines of the function
   list -10     # displays negative 10 lines i.e. above current point in source code.

Printing information:
    print iCount
   #   prints value of iCount variable
    print $eax
   #   prints value in eax register
    print my_func(10+2)    #   prints the return value of myFunc(12)    
    printf "%s\n" myPtr
   #   prints the string pointed to by myPtr

Change variables:
    set  iCount=100

Control-flow statements:
Setting a breakpoint:
    break main                     #   set breakpoint on a function    
    break  myfile.cpp:10    #   set breakpoint on Filename:Linenumber


    # Attach a conditional to a bnum where bnum is a breakpoint, watchpoint or catchpoint
    cond bnum x != 0

    (gdb) step  [count]  #   step to next source level statement (includes entering into a function call)
    (gdb) stepi  [count]  #   step to next machine level instruction (includes step-into a function call)
    (gdb) next   [count]  #   step to next source level statement (stepping over a function call)
    (gdb) nexti   [count]  #   step to next machine level instruction (stepping over a function call)

    # Useful for reaching a function or skipping over a loop
    (gdb) until [location]    # continue execution until you reach the location.

    (gdb) continue  [ignore-count]      # continue execution with optional count to ignore a breakpoint
    (gdb) call  add(10,20)   # call any function from gdb
    (gdb) finish      # finish the current function and stop in calling function
    (gdb) return    # force return to calling function
    (gdb) advance myfunc   # jump to an arbitrary location in the program

Autocomplete in gdb: (Press tab at end of word or alt+?)
    (gdb) break m(TAB)
    (gdb) br 'myFun(TAB)
    (gdb) br 'myFun(Alt+?)
    (gdb) print 'mystruct.my(Alt+?)       #   displays all members of mystruct
Break Command Lists:   a)break 403 if x>0      commands
        silent
        printf "x is %d\n", x
        continue
      end
    b) break myFunction
        commands
            silent
     
set x = y + 4
            continue
        end

  
Stack frame operations:
    frame   
#display brief description of currently selected stack frame
    info frame [addr]   #verbose description about stack frame
    frame n    # select frame by number
    frame addr  #  useful to select bug-corrupted frame by address rather than frame number

    up (-)N    # move up by (-)N stack frames
    down
(-)N    # move down to (-)N stack frames downward
    backtrace [full (-)N]
   #   show function call-stack upto N depth, Full shows locals also for current thread
  thread apply all backtrace [full  (-)N] # displays backtrace for all threads in a multi-threaded application.

    info args    # display arguments of current stack frame
    info locals    # display in-scope (static/auto) variables of current stack frame.
    info catch    # display info on exception handlers in current stack-frame
  Automatic display of info:
    info display    # lists the various auto displays
    display /fmt expression
    disable|enable display dnum
    display    # forces output of all the enabled display-expressions
    Note: GDB automatically disables display of a local variable when it goes out of scope.

Examining Memory:
    a) (gdb) info line main
            Line 9 of "hi.cpp" starts at pc 0x000c and ends at 0x0100
       (gdb) disassemble /m 0x000c, 0x0100       # /m = mixed source+assembly, /r = raw machine instructions

    b) # n=Count, f=format (`x', `d', `u', `o', `t', `a', `c', `f', `s'), units=(byte=1, halfword=2, word=4, giant=8)
        x /10s1 &myarray    # print 10 bytes string of myarray

Attaching to a running process by PID:
    attach 1234      # attaches to external process by PID and stops it 
    break myBuggyFunction     # set break point
    continue                              # continue execution of stopped process
    detach                                # gdb detaches from the running process. Can run/attach another process from hereon.

Kill the debugee process:
Note:  a) If you exit gdb while you have an attached process, you detach that process.
b) If you use the
run command (while attached), you kill that process.
c) By default,
gdb asks for confirmation if you try to do either of these things
    kill   # useful for a) recompile while retaining breakpoints b) switch to debugging the proc's core dump
  
Choose Files:
1) Take symbols from a.syms, execute a.out, use core, and attach to pid 1234
    gdb -symbols a.syms   -exec a.out   -core core    -pid 1234
2) Take symbol-table from the executable, use core and attach to pid 1234
    gdb -se a.out -core core -pid 1234
3) Standalone gdb commands to choose symbol-file, exec-file , core-file:
    file progAndsym.out
   #   choose both symbol and executable files
    exec-file prog.out
    symbol-file  symbols.sym
    core-file core.1234

Gdb help:
    a) help command
    b) apropos search-term   # similar to apropos command to search based on search terms
    c) info  # help on program being debugged       

       help info  #see what all commands are possible for info
    d) set radix 10
       show radix    #   display current gdb settings for radix
       show          #   by default displays all current gdb settings       
       help show    #   see what all commands are possible for show

Saving GDB command history:    set history filename fname
    set history save on|off

Running shell or make commands:
    a) shell ls
    b) make clean
       make all

Logging gdb output:
  set logging on|off
    set logging file mygdb.log,
    set logging overwrite on|off    #   set append on/off
    set logging redirect on|off    #   redirect output to logfile AND console
    show logging    #   show current logging settings

Get/Set GDB settings: # better to set/get environment variables through .profile/.login files.
    a) cd directory    # set current directory
        pwd
    b) info proc        # displays current directory of debugged process at any time
    c) (gdb) show paths

        (gdb) path directory
    d) (gdb) show environment [varname]
        (gdb) set environment varname [=value]   #  set value as null if optinal value is missing
       (gdb) unset env varname

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.