Debugging with GDB - Running Programs Under GDB (2024)

Go to the previous, next section.

When you run a program under GDB, you must first generatedebugging information when you compile it.You may start it with its arguments, if any, in an environment of yourchoice. You may redirect your program's input and output, debug analready running process, or kill a child process.

Compiling for debugging

In order to debug a program effectively, you need to generatedebugging information when you compile it. This debugging informationis stored in the object file; it describes the data type of eachvariable or function and the correspondence between source line numbersand addresses in the executable code.

To request debugging information, specify the `-g' option when you runthe compiler.

Many C compilers are unable to handle the `-g' and `-O'options together. Using those compilers, you cannot generate optimizedexecutables containing debugging information.

GCC, the GNU C compiler, supports `-g' with or without`-O', making it possible to debug optimized code. We recommendthat you always use `-g' whenever you compile a program.You may think your program is correct, but there is no sense in pushingyour luck.

When you debug a program compiled with `-g -O', remember that theoptimizer is rearranging your code; the debugger shows you what isreally there. Do not be too surprised when the execution path does notexactly match your source file! An extreme example: if you define avariable, but never use it, GDB never sees thatvariable--because the compiler optimizes it out of existence.

Some things do not work as well with `-g -O' as with just`-g', particularly on machines with instruction scheduling. If indoubt, recompile with `-g' alone, and if this fixes the problem,please report it as a bug (including a test case!).

Older versions of the GNU C compiler permitted a variant option`-gg' for debugging information. GDB no longer supports thisformat; if your GNU C compiler has this option, do not use it.

Starting your program

run
r
Use the run command to start your program under GDB. You mustfirst specify the program name(except on VxWorks)with an argument to GDB (see section Getting In and Out of GDB), or by using the file or exec-filecommand (see section Commands to specify files).

If you are running your program in an execution environment thatsupports processes, run creates an inferior process and makesthat process run your program. (In environments without processes,run jumps to the start of your program.)

The execution of a program is affected by certain information itreceives from its superior. GDB provides ways to specify thisinformation, which you must do before starting your program. (Youcan change it after starting your program, but such changes only affectyour program the next time you start it.) This information may bedivided into four categories:

The arguments.
Specify the arguments to give your program as the arguments of therun command. If a shell is available on your target, the shellis used to pass the arguments, so that you may use normal conventions(such as wildcard expansion or variable substitution) in describingthe arguments. In Unix systems, you can control which shell is usedwith the SHELL environment variable. See section Your program's arguments.
The environment.
Your program normally inherits its environment from GDB, but you canuse the GDB commands set environment and unsetenvironment to change parts of the environment that affectyour program. See section Your program's environment.
The working directory.
Your program inherits its working directory from GDB. You can setthe GDB working directory with the cd command in GDB.See section Your program's working directory.
The standard input and output.
Your program normally uses the same device for standard input andstandard output as GDB is using. You can redirect input and outputin the run command line, or you can use the tty command toset a different device for your program.See section Your program's input and output.

Warning: While input and output redirection work, you cannot usepipes to pass the output of the program you are debugging to anotherprogram; if you attempt this, GDB is likely to wind up debugging thewrong program.

When you issue the run command, your program begins to executeimmediately. See section Stopping and Continuing, for discussionof how to arrange for your program to stop. Once your program hasstopped, you may call functions in your program, using the printor call commands. See section Examining Data.

If the modification time of your symbol file has changed since the lasttime GDB read its symbols, GDB discards its symboltable, and reads it again. When it does this, GDB tries to retainyour current breakpoints.

Your program's arguments

The arguments to your program can be specified by the arguments of therun command. They are passed to a shell, which expands wildcardcharacters and performs redirection of I/O, and thence to your program.Your SHELL environment variable (if it exists) specifies whatshell GDB uses. If you do not define SHELL,GDB uses /bin/sh.

run with no arguments uses the same arguments used by the previousrun, or those set by the set args command.

set args
Specify the arguments to be used the next time your program is run. Ifset args has no arguments, run executes your programwith no arguments. Once you have run your program with arguments,using set args before the next run is the only way to runit again without arguments.
show args
Show the arguments to give your program when it is started.

Your program's environment

The environment consists of a set of environment variables andtheir values. Environment variables conventionally record such things asyour user name, your home directory, your terminal type, and your searchpath for programs to run. Usually you set up environment variables withthe shell and they are inherited by all the other programs you run. Whendebugging, it can be useful to try running your program with a modifiedenvironment without having to start GDB over again.

path directory
Add directory to the front of the PATH environment variable(the search path for executables), for both GDB and your program.You may specify several directory names, separated by `:' orwhitespace. If directory is already in the path, it is moved tothe front, so it is searched sooner.

You can use the string `$cwd' to refer to whatever is the currentworking directory at the time GDB searches the path. If youuse `.' instead, it refers to the directory where you executed thepath command. GDB replaces `.' in thedirectory argument (with the current path) before addingdirectory to the search path.

show paths
Display the list of search paths for executables (the PATHenvironment variable).
show environment [varname]
Print the value of environment variable varname to be given toyour program when it starts. If you do not supply varname,print the names and values of all environment variables to be given toyour program. You can abbreviate environment as env.
set environment varname [=] value
Set environment variable varname to value. The valuechanges for your program only, not for GDB itself. value maybe any string; the values of environment variables are just strings, andany interpretation is supplied by your program itself. The valueparameter is optional; if it is eliminated, the variable is set to anull value.

For example, this command:

set env USER = foo

tells a Unix program, when subsequently run, that its user is named`foo'. (The spaces around `=' are used for clarity here; theyare not actually required.)

unset environment varname
Remove variable varname from the environment to be passed to yourprogram. This is different from `set env varname =';unset environment removes the variable from the environment,rather than assigning it an empty value.

Warning: GDB runs your program using the shell indicatedby your SHELL environment variable if it exists (or/bin/sh if not). If your SHELL variable names a shellthat runs an initialization file--such as `.cshrc' for C-shell, or`.bashrc' for BASH--any variables you set in that file affectyour program. You may wish to move setting of environment variables tofiles that are only run when you sign on, such as `.login' or`.profile'.

Your program's working directory

Each time you start your program with run, it inherits itsworking directory from the current working directory of GDB.The GDB working directory is initially whatever it inheritedfrom its parent process (typically the shell), but you can specify a newworking directory in GDB with the cd command.

The GDB working directory also serves as a default for the commandsthat specify files for GDB to operate on. See section Commands to specify files.

cd directory
Set the GDB working directory to directory.
pwd
Print the GDB working directory.

Your program's input and output

By default, the program you run under GDB does input and output tothe same terminal that GDB uses. GDB switches the terminal toits own terminal modes to interact with you, but it records the terminalmodes your program was using and switches back to them when you continuerunning your program.

info terminal
Displays information recorded by GDB about the terminal modes yourprogram is using.

You can redirect your program's input and/or output using shellredirection with the run command. For example,

run > outfile

starts your program, diverting its output to the file `outfile'.

Another way to specify where your program should do input and output iswith the tty command. This command accepts a file name asargument, and causes this file to be the default for future runcommands. It also resets the controlling terminal for the childprocess, for future run commands. For example,

tty /dev/ttyb

directs that processes started with subsequent run commandsdefault to do input and output on the terminal `/dev/ttyb' and havethat as their controlling terminal.

An explicit redirection in run overrides the tty command'seffect on the input/output device, but not its effect on the controllingterminal.

When you use the tty command or redirect input in the runcommand, only the input for your program is affected. The inputfor GDB still comes from your terminal.

Debugging an already-running process

attach process-id
This command attaches to a running process--one that was startedoutside GDB. (info files shows your activetargets.) The command takes as argument a process ID. The usual way tofind out the process-id of a Unix process is with the ps utility,or with the `jobs -l' shell command.

attach does not repeat if you press RET a second time afterexecuting the command.

To use attach, your program must be running in an environmentwhich supports processes; for example, attach does not work forprograms on bare-board targets that lack an operating system. You mustalso have permission to send the process a signal.

When using attach, you should first use the file commandto specify the program running in the process and load its symbol table.See section Commands to specify files.

The first thing GDB does after arranging to debug the specifiedprocess is to stop it. You can examine and modify an attached processwith all the GDB commands that are ordinarily available when you startprocesses with run. You can insert breakpoints; you can step andcontinue; you can modify storage. If you would rather the processcontinue running, you may use the continue command afterattaching GDB to the process.

detach
When you have finished debugging the attached process, you can use thedetach command to release it from GDB control. Detachingthe process continues its execution. After the detach command,that process and GDB become completely independent once more, and youare ready to attach another process or start one with run.detach does not repeat if you press RET again afterexecuting the command.

If you exit GDB or use the run command while you have anattached process, you kill that process. By default, GDB asksfor confirmation if you try to do either of these things; you cancontrol whether or not you need to confirm by using the setconfirm command (see section Optional warnings and messages).

Killing the child process

kill
Kill the child process in which your program is running under GDB.

This command is useful if you wish to debug a core dump instead of arunning process. GDB ignores any core dump file while your programis running.

On some operating systems, a program cannot be executed outside GDBwhile you have breakpoints set on it inside GDB. You can use thekill command in this situation to permit running your programoutside the debugger.

The kill command is also useful if you wish to recompile andrelink your program, since on many systems it is impossible to modify anexecutable file while it is running in a process. In this case, when younext type run, GDB notices that the file has changed, andreads the symbol table again (while trying to preserve your currentbreakpoint settings).

Additional process information

Some operating systems provide a facility called `/proc' that canbe used to examine the image of a running process using file-systemsubroutines. If GDB is configured for an operating system with thisfacility, the command info proc is available to report on severalkinds of information about the process running your program.

info proc
Summarize available information about the process.
info proc mappings
Report on the address ranges accessible in the program, with informationon whether your program may read, write, or execute each range.
info proc times
Starting time, user CPU time, and system CPU time for your program andits children.
info proc id
Report on the process IDs related to your program: its own process ID,the ID of its parent, the process group ID, and the session ID.
info proc status
General information on the state of the process. If the process isstopped, this report includes the reason for stopping, and any signalreceived.
info proc all
Show all the above information about the process.

Debugging programs with multiple threads

In some operating systems, a single program may have more than onethread of execution. The precise semantics of threads differ fromone operating system to another, but in general the threads of a singleprogram are akin to multiple processes--except that they share oneaddress space (that is, they can all examine and modify the samevariables). On the other hand, each thread has its own registers andexecution stack, and perhaps private memory.

GDB provides these facilities for debugging multi-threadprograms:

  • automatic notification of new threads
  • `thread threadno', a command to switch among threads
  • `info threads', a command to inquire about existing threads
  • thread-specific breakpoints
Warning: These facilities are not yet available on everyGDB configuration where the operating system supports threads.If your GDB does not support threads, these commands have noeffect. For example, a system without thread support shows no outputfrom `info threads', and always rejects the thread command,like this:
(gdb) info threads(gdb) thread 1Thread ID 1 not known. Use the "info threads" command tosee the IDs of currently known threads.

The GDB thread debugging facility allows you to observe allthreads while your program runs--but whenever GDB takescontrol, one thread in particular is always the focus of debugging.This thread is called the current thread. Debugging commands showprogram information from the perspective of the current thread.

Whenever GDB detects a new thread in your program, it displaysthe target system's identification for the thread with a message in theform `[New systag]'. systag is a thread identifierwhose form varies depending on the particular system. For example, onLynxOS, you might see

[New process 35 thread 27]

when GDB notices a new thread. In contrast, on an SGI system,the systag is simply something like `process 368', with nofurther qualifier.

For debugging purposes, GDB associates its own threadnumber--always a single integer--with each thread in your program.

info threads
Display a summary of all threads currently in yourprogram. GDB displays for each thread (in this order):
    the thread number assigned by GDB
    the target system's thread identifier (systag)
    the current stack frame summary for that thread

An asterisk `*' to the left of the GDB thread numberindicates the current thread.

For example,

(gdb) info threads 3 process 35 thread 27 0x34e5 in sigpause () 2 process 35 thread 23 0x34e5 in sigpause ()* 1 process 35 thread 13 main (argc=1, argv=0x7ffffff8) at threadtest.c:68
thread threadno
Make thread number threadno the current thread. The commandargument threadno is the internal GDB thread number, asshown in the first field of the `info threads' display.GDB responds by displaying the system identifier of the threadyou selected, and its current stack frame summary:
(gdb) thread 2[Switching to process 35 thread 23]0x34e5 in sigpause ()

As with the `[New ...]' message, the form of the text after`Switching to' depends on your system's conventions for identifyingthreads.

Whenever GDB stops your program, due to a breakpoint or asignal, it automatically selects the thread where that breakpoint orsignal happened. GDB alerts you to the context switch with amessage of the form `[Switching to systag]' to identify thethread.

See section Stopping and starting multi-thread programs, formore information about how GDB behaves when you stop and startprograms with multiple threads.

See section Setting watchpoints, for information aboutwatchpoints in programs with multiple threads.

Debugging programs with multiple processes

GDB has no special support for debugging programs which createadditional processes using the fork function. When a programforks, GDB will continue to debug the parent process and thechild process will run unimpeded. If you have set a breakpoint in anycode which the child then executes, the child will get a SIGTRAPsignal which (unless it catches the signal) will cause it to terminate.

However, if you want to debug the child process there is a workaroundwhich isn't too painful. Put a call to sleep in the code whichthe child process executes after the fork. It may be useful to sleeponly if a certain environment variable is set, or a certain file exists,so that the delay need not occur when you don't want to run GDBon the child. While the child is sleeping, use the ps program toget its process ID. Then tell GDB (a new invocation ofGDB if you are also debugging the parent process) to attach tothe child process (see section Debugging an already-running process). From that point on you can debugthe child process just like any other process which you attached to.

Go to the previous, next section.

Debugging with GDB - Running Programs Under GDB (2024)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Jerrold Considine

Last Updated:

Views: 6366

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.