GDB

Debug A Program Started By A Script

1. Introduction

When debugging a program, things can get tricky if it is launched via a script. The script might set environment variables, pass specific arguments, or even invoke the program indirectly, making it challenging to attach GDB.

2. Lab

2.1. Program

  
#include <stdio.h>

int main(int argc, char** argv)
{
    printf("hello\n");
    return 0;
}
  
  
$ gcc -g demo.c -o demo
  
  
echo "====  begin   ===="
./demo
echo "==== end     ===="
  

2.2. Debug

  
$ gdb --args bash run.sh
  
  
(gdb) set detach-on-fork off
  
  
(gdb) set follow-fork-mode child
  
  
(gdb) catch exec
  
  
(gdb) run
  
  
# console log
Starting program: /usr/bin/bash run.sh

====  begin   ====
[Attaching after Thread 0x7ffff7f73740 (LWP 42499) fork to child process 42502]
[New inferior 2 (process 42502)]
process 42502 is executing new program: /opt/app/demo
[Switching to process 42502]

Thread 2.1 "demo" hit Catchpoint 1 (exec'd /opt/app/demo), 0x00007ffff7fe4540 in ?? () from /lib64/ld-linux-x86-64.so.2
  
  
(gdb) break main
  
  
(gdb) continue
  
  
# console log
Continuing.

Thread 2.1 "demo" hit Breakpoint 2.1, main (argc=1, argv=0x7fffffffdc38) at demo.c:5
5           printf("hello\n");
  
  
(gdb) info inferiors
  
  
# console log
  Num  Description       Connection           Executable        
  1    process 42499     1 (native)           /usr/bin/bash     
* 2    process 42502     1 (native)           /opt/app/demo
  
  
(gdb) continue
  
  
# console log
Continuing.
hello
[Inferior 2 (process 42502) exited normally]
  
  
(gdb) info inferiors
  
  
# console log
  Num  Description       Connection           Executable        
  1    process 42499     1 (native)           /usr/bin/bash     
* 2    <null>  42502     1 (native)           /opt/app/demo
  
  
(gdb) inferior 1
  
  
# console log
[Switching to inferior 1 [process 42499] (/usr/bin/bash)]
[Switching to thread 1.1 (Thread 0x7ffff7f73740 (LWP 42499))]
  
  
(gdb) continue
  
  
# console log
Continuing.
==== end     ====
[Inferior 1 (process 42499) exited normally]
  

3. Cheatsheets

  
set confirm off
set pagination off

set detach-on-fork off
set follow-fork-mode child

catch exec
  
  
$ gdb -q -x debug.gdb --args bash run.sh
  

References