GDB Series four runs the program in GDB

Source: Internet
Author: User
Tags switches

Before you start running the program in GDB, you need to generate debugging information at compile time.
You can start gdb with parameters (if any) in your chosen environment. If you are debugging locally, you can redirect the input output, debug a run
process, or to end a process.

4.1 Compiling for debugging
For an effective debug program, you need to generate debugging information at compile time. Debugging information is stored in the target file, and the debug information describes the type of data and functions,
The correspondence between the source code and the executable code.
Specifying the compiler's '-G ' option at compile time can produce debug information.
You can specify the compiler to optimize with the '-o ' option when compiling programs that are published to your customers. However, many compilers cannot process the '-G ' and '-o ' options at the same time. If you use the
Are these compilers, you do not get an optimized executable program with debugging information.
The Gcc,gnu/C + + compiler, with or without the '-o ' option, can use the '-G ' option, so GDB can debug the optimized code. We recommend that you always compile the program
is to use '-G '. You may think your program is correct, but never take a chance.
Keep in mind that when you debug a program compiled with '-g-o ', the optimizer has re-queued your code, and the debugger displays the code that is actually compiled. In the execution path and you
Do not be too surprised when the source code is inconsistent! An extreme example: If a variable is defined but never used, GDB cannot find it-because the optimizer has
It's optimized out.
Programs that are compiled with '-g-o ' and only '-G ' are sometimes quite different, especially on machines with instruction scheduling. If in doubt, then use only with '-G ' compilation, if this version
This fixes the problem, please send us a report (including a test case). For more debugging of optimized code, see section 8.2 [Variables], page 76.
The earlier GNU C compiler allowed a '-gg ' variant option to generate debug information. GDB no longer supports this format; If your GNU C compiler has this option, do not
It's been used again.
GDB knows the precompiled macro and can display the expanded type of the macro (see chapter Nineth [Macro], page 101). Because the '-G ' option produces too many debugging information, most compilers do not produce
Information with the compiled macro. GCC3.1 version and thereafter can provide macro information, if at compile time specify the '-gdwarf-2 ' and '-g3 ' option; the previous option generated dwarf
Debug information in 2 format, which produces "extra information". We hope to find a streamlined way to represent macro information in the future so that only a '-G ' option is available.

4.2 Starting the program
Run
R Start your program with the Run command in GDB. You specify the program name to debug when you start GdB (VxWorks exception) (see chapter II [Entering and leaving GDB]),
or use the file or Exec-file command (see section 15.1 [Commands for specifying a file], page 155).
If you are running GDB in a multi-process-enabled environment, the Run command creates a child process to run your program. In a system that does not support multi-process environments,
Run jumps to the beginning of the program being debugged. Other goals, such as ' remote ', are always running. If you have an error message similar to the following:
The "remote" target does not a support "run".
Try "Help target" or "continue".
Then use ' Continue ' to continue running your program. You may need to load first (see [Load], page 169).
The execution of a program is always affected by certain information obtained from its superiors. GDB can specify those virtual ouch you want to set before starting the program (you
Can be changed after starting a program, but only when it is next run). This information can be divided into 4 categories:
The arguments.
Use the parameters of your program as parameters of the Run command. If you have Shell,shell in your environment that can be used to pass parameters, then you can do it in a normal way.
(such as wildcard expansion and variable substitution) to describe the parameters. In a UNIX system, you can use the environment variable shell to control the shell. see section 4.3 [Program
Parameters], 27 pages.
The environment.
Your program inherits environment variables from GDB, and you can use GDB command set environment and unset environment to change some of the things that affect your program.
Environment variables. See Section 4.4, "Environment],28 page of the program."
The working directory.
Your program inherits the working directory from GDB. You can use the GDB command CD to change the working directory. See section 4.5, [working directory of the Program], page 29.
The standard input and output.
Your program uses the same standard input and output as GDB. You can redirect the input and output from the Run command line, or you can use the TTY command for your program
Set up a different device. See section 4.6, [input and output of the program], 29 pages.
Warning: After the input and output redirection is in effect, you can no longer use the pipeline to pass the output of the program to another program; If you try that,
GDB is very likely to end debugging this wrong program.
After you execute the Run command, your program will start executing immediately. See chapter Fifth [Stop and Continue], page 39, where you discuss how to plan for interrupting your program. One
Once your program is interrupted, you can invoke the function in your program, using the print or call command. See chapter eighth [test data], page 75.
If the modification time of the symbol file has changed since the last time GDB was read into the symbol table, GDB discards the existing symbol table and reads it back in. Re-read in
Symbol table, GDB will try to preserve your current breakpoint settings.
Start different languages may have different names for the main functions. The name of the main function is always "main" for C/s + +, and some languages such as ADA do not need
To specify a specific name for their main function. Depending on the programming language, the debugger can easily start executing the program and in the entry point of the main function
Broken.
The function of the ' start ' command is equivalent to executing the ' run ' command after setting a temporary breakpoint in the main function entry point. Some programs contain a prior to the main program
Processing period, some startup code will be executed during the processing period. This depends on which language you use to write the program. For example, C + +, the constructor will be static before main
and global variable invocation. Therefore, it is possible for the debugger to break the program before the main function. The temporary breakpoint is also retained to interrupt execution of the program.
The ' start ' parameter will be passed to your program. These parameters are given as characters to the ' run ' command. Note that if you call ' start ' with no arguments next time, or
' Run ', these parameters will be reused.
Sometimes it is necessary to debug the program during the processing period. In this case, the start command breaks at the main function entry point too late, the only time it has been processed
。 In this case, it is possible to set a breakpoint on the processing period code in the running situation.

4.3 Program parameters
Parameters can be specified by the parameters of the Run command. Parameters are passed to your program by the shell, and the shell expands the wildcard character and performs the redirect. Your shell environment variable
(if any) determines which shell is used by GDB. If you do not define the shell, GDB uses the default shell (under Unix ' bin/sh ').
In non-UNIX systems, the program is usually called directly by GDB, and GDB will use the corresponding

The system is used to simulate I/O redirection, and the spread of the wildcard is added by the program
The duration code is done, not by the shell.
The Run command without parameters uses the parameters of the previous Run command, or the parameters set by the set args command.
Set args
Set the parameters for your next execution of the program. If set args does not have parameters, run executes the program without parameters. Once you have the run program with parameters
, the next execution without parameters is only the set args command with no parameters.
Show args
Displays the parameters that are passed to the program when it is started.

4.4 Environment of the program
An environment consists of a combination of environment variables and the values of environment variables. Environment variables can easily record something, such as your user name,
Home directory, terminal type, program execution search path, and so on. Environment variables are usually set by the shell, and these variables can be used by other programs
It's a promise. This is useful when debugging, and GDB does not have to reboot to experiment with a changed environment.
Path directory
Add Diretory (the executable's search path) ahead of the PATH environment variable. The path used by GDB will not change. You can specify multiple path names
The use of space or system-dependent (Unix ': ', Ms_dos, ms-windows '; ) Delimiter class split if directory is already in path,
This directory is moved to the front of the path to speed up the search.
You can use ' $cwd ' to refer to the current working directory when GDB searches for paths. If you use '. ' Instead, it represents the target when you execute the path command
Recorded. GDB replaces '. ' with the current path before it joins the path to path.
Show paths
Displays a list of search paths for executable programs (PATH environment variable).
Show environment [VarName]
Prints the value of an environment variable named varname. If you do not provide varname, print the names and values of all environment variables. You can abbreviate
Environment is ENV.
Set environment VarName [=value]
Set the environment variable varname to value. This value is only changed for your program, and GDB itself does not change. Value can make any string; environment variable
is a string, your program is responsible for the translation, if it is deleted, the value of the variable is set to a null value. For example, command:
Set env USER = foo
Tells the program to be debugged that the next time the run is executed, its user is ' foo '. (the spaces near ' = ' are for clarity; spaces are not required)
unset Environment varname
Delete the environment variables passed to the program. Unlike ' Set env varname = ', unset environment removes the variable from the environment variable, not
Set a null value for it.
Warning: In UNIX systems, GDB executes the program with the shell, and the shell is determined by the shell (or '/bin/sh ' if any). If the shell environment changes
The specified shell has initialization files-for example C-shell '. CSHRC ', bash '. BASHRC '-variables defined in these files will affect your program.
You can also move variables that are only used when you log in to other files, such as '. Login ' or '. Profile '.

4.5 Working directory of the program
Each time you start a program with run, the program inherits the working directory from the current working directory of GDB. GDB inherits its work from its parent process (usually the shell)
directory, and you can use a CD to specify a new working directory in GDB.
GDB's working directory is the default directory when GDB operates files. Participate in section 15.1 [File command], page 155.
CD Directory
Specify GDB's working directory as Directory
PWD Print GDB's working directory
It is often difficult to find the current working path of the debugged program (because it can be changed at run time). If you are in a system that supports the '/proc ' file system
To run GDB, you can use the info proc command to find the working directory of the currently debugged program. (see section 18.1.3, [SVR4 Process Information],183 page)

4.6 program input and output
  by default, the program running in GDB enters the output on the same terminal as GDB. GDB will switch to its own terminal mode when interacting with you,
but it will remember the terminal mode of your program and then switch to that mode while continuing to run the program.
Info Terminal
    Displays the terminal mode that GDB recorded for your program.
  You can redirect the program's input/output with the Run command. For example:
    run > outfile
  Start running the program and print output to file ' outfile '.
  Another command that specifies the input and output of a program is a TTY command. This command takes a file name as a parameter and then takes the file as the default for the next
Run command. It can also reset the control terminal for the child process. For example,
    tty/dev/ttyb
directs the input and output of the process running by the next Run command to '/dev/ttyb ' and takes this as a control terminal. The
Run command changes the settings of the TTY command for the input and output devices, but does not change its control terminal.
using the TTY command or redirecting input in the Run command will only affect the program you are debugging. GDB's input still comes from your terminal. TTY is the alias of set Inferior-tty.
  You can use the show Inferior-tty command to go to GDB to show that the program will use the terminal name.
Set INFERIOR-TTY/DEV/TTYB
    set the TTY device for the debugger to/dev/ttyb
Show Inferior-tty
     Displays the current TTY device name for the debugged program

4.7 Debugging a process that is already running
Attach Process-id
    This command attach to a process that starts outside of GDB. (Info files shows your current active target) This command requires a
    ID as a parameter. Usually use the PS tool to find the ID of a UNIX process, or use the ' jobs-l ' shell command.
    After you execute the attach command, press ENTER attach will not be executed again.
  The Attach command is only valid in an environment that supports processes, for example, attach is not available on bare metal without an operating system. You must have permission to send a signal to the
process.
  When you execute the attach command, the debugger first locates the executable program of the process under the current working directory, and if it is not found, then searches the path with the source
code file (see section 7.5 [Specify Source code], page 70). You can also use the file command to load an executable file. See section 15.1, [commands for specifying files], page 155.
  GDB The first thing that happens after the process is ready to be debugged is to break the process. Commands that can be used on a process that is started by run can also be used on your
attach process, and you can check and modify the process. You can insert a breakpoint; You can step and continue; You can modify the memory.
If you want the process to continue, you can continue with the continue command after attach.
Detach
    after debugging is complete, you can use detach to release the GDB control of the process. After the detach process, the process continues execution. Detach Command
   , the process and gdb are not related, you can also attach to another process or start a program with run. Detach
    After execution, press ENTER will not repeat.
  If you attach a process, exiting GDB will detach the process. If you start with the Run command, you will kill the process. The default
, GDB will ask for your confirmation, you can use the set confirm command to control whether you need confirmation (see section 19.7 [Optional Warning and Message],213 page).

4.8 Kill child Process
Kill kills a child process running in GDB
This command is useful when you want to debug a core dump rather than a process. While the program is running, GDB ignores the core dump

In a system, if you set a breakpoint in GDB for this program, the program will not run outside of GDB. You can use the KILL command to <BR.
/> Let the program run outside of GDB.
When you run the program, the KILL command also helps to re-edit and reconnect the program, and some systems are unlikely to do so. In this case
, the next time the Run command is executed, GDB can know that the program has changed and will re-read the symbol table (while preserving your current
Breakpoint settings).

4.9 Debugging multithreaded processes
In some operating systems, such as HP-UX and Solaris, a program may have multiple threads. Thread-precise concepts are different with each operating system
, but in general, a process with multiple threads is similar to a multi-process, except that multithreading shares an address space (that is, they can check and modify
Same variable). On the other hand, each thread has its own register and execution stack, and it may have its own private storage space.
GDB provides a number of tools for debugging Multithreading:
Automatic notification of new threads
' Thread Threadno ', switching threads
' Info threads ', query thread
' thread apply [Threadno] [all] args ', execute command on the thread list
Thread-specific breakpoints
' Set print Thread-events ', which controls when threads start and end printing messages
Warning: Not all GDB configurations support these tools in each supported thread's operating system. If your GDB does not support threading, this life
The order is void. For example, the ' Info Threads ' command in a system that does not support threading cannot output information, and it rejects the thread command, as follows:
(GDB) Info threads
(GDB) Thread 1
Thread ID 1 not known. Use the ' Info Threads ' command to
See the IDs of currently known threads.
The GDB thread debugging tool can observe all threads of a process, and once GDB controls the thread, the thread is always the focus of debugging. This thread
called the current thread. The debug command displays information about the process from the perspective of the current thread.
Once gdb perceives the new thread of the process, GDB displays the identity of the target system in the form of ' [New Systag] '. Systag is the identity of the thread, each
Systems are different. For example, when GdB discovers a new thread, in Gnu/linux you may see
[New Thread 46912507313328 (LWP 25582)].
In the SGI system, Systag is simply shaped like ' process 368 ', with no more information.
For debugging purposes, GDB itself will give the thread a number – always an integer.
Info threads
Displays a general summary of the threads in the current process. GDB displays each thread (in this order):
1.GDB assigned thread number
2. Thread identification of the target system (SYSTAG)
3. Overview of thread current stack
The asterisk ' * ' on the left side of the thread number indicates that this thread is the current thread. For example:
(GDB) Info threads
3 Process + thread 0x34e5 in Sigpause ()
2 process, thread, 0x34e5 in Sigpause ()
* 1 process, thread, main (argc=1, ARGV=0X7FFFFFF8)
At threadtest.c:68
In the HP-UX system:
For debugging purposes, GDB assigns a thread number to each thread in the process (assigning small integers in the thread creation order).
Whenever gdb perceives a new thread, it displays GDB's own thread number and the thread flag of the target system in the form of ' [New Systag] '.
Systag are thread identities and may be different under each system. For example, GDB perceives a new thread, and on HP-UX, you can see
[New thread 2 (System thread 26594)].
Info threads
Displays a summary of all threads. GDB displays each thread (in this order):
1.GDB assigned thread number
2. Thread identification of the target system (SYSTAG)
3. Overview of thread current stack
The asterisk ' * ' on the left side of the thread number indicates that this thread is the current thread. For example:
(GDB) Info threads
* 3 System thread 26607 worker (wptr=0x7b09c318 "@")
At quicksort.c:137
2 system thread 26606 0x7b0030d8 in __ksleep ()
From/usr/lib/libc.2
1 system thread 27905 0x7b003498 in _brk ()
From/usr/lib/libc.2
In the Solaris system, you can use a Solaris-specific command to display more information:
Maint Info sol-threads
Displays information about the Solaris user thread.
Thread Threadno
Sets the thread that Threadno points to the current thread. The parameter threadno of this command is the thread number within GDB, which is ' info threads '
The command displays the first column.
GDB Displays the system identity of the thread you selected and a summary of its current stack:
(GDB) Thread 2
[Switching to process + thread 23]
0x34e5 in Sigpause ()
Along with ' [New ...] ' Message, the text form after ' switching to ' is determined by your system thread identity representation.
thread apply [Threadno] [all] command
The thread apply command allows you to execute a command called commands on one or more threads. Specify the threadno you want to manipulate with the parameter
The number of threads. Can be a single thread number, ' info threads ' Displays the first column, or it can be a thread range, like 2-4. To manipulate all
thread, typing thread, apply all command.
Set Print Thread-events
Set Print thread-events on
Set Print thread-events off
GDB detects that the set Print Thread-events command can turn printing information on or off when a new thread is started or when the thread ends. Default
, if the target system supports it, the information will be printed when these events occur. Note that this information is not necessarily
Can be turned off in the standard system.
Show Print Thread-events
Displays whether the information is printed when GDB perceives the thread to start or end.
Determined by a breakpoint or signal, whenever GDB stops the program, it chooses the breakpoint or the thread on which the signal occurs. GDB will use ' [Switching to Syst
AG] ' form identifies the thread prompting the thread to toggle the context.
For more information on GDB's behavior to stop starting multithreaded routines, see section 5.4, "Stopping the kernel-initiated multithreaded],59 page."
For more information on the observer point for multithreaded programs, see 5.1.2[Setting the Observer Point],44 page.

4.10 Debugging Multiple Programs
In most systems, GDB does not provide special support for programs that can use fork calls to create additional processes. GDB will continue debugging when the program creates the child process
The parent process, and the child process is unaffected. If you have previously set a breakpoint on the child process's code, the child process will be terminated by the sigtrap signal.
However, if you want to debug a child process, there is a less cumbersome alternative. Call the sleep tone in the child process code after the fork call
Use. If the call to sleep code is determined by some environment variables or the existence of a file, it is convenient: if you do not want to debug Wahabbi
Not set these variables or delete files. When the child process sleeps, the PS program is used to get the process ID. Then use GDB to attach this.
On a child process, if you are debugging the parent process, you need to start a new GDB instance, see the 4.7[attach],30 page. You can be like attach to other
Process to start debugging the child process.
On some systems, GDB provides debugging support for programs that create child processes with fork or vfork calls. Currently, only HP-UX (11.x and later versions) and
Gnu/linux (2.5.60 kernel version and subsequent) provides support for this feature.
By default, when a child process is created, GDB continues to debug the parent process, and the child process is unaffected.
If you want to debug a child process, use the command
Set Follow-fork-mode.
Set Follow-fork-mode mode
Sets the debugger's response to a fork or vfork call. Fork or Vfork creates a child process. The mode parameter can be:
The parent fork then debugs the original process. The child process is not affected by the shadow
Ring. This is the default way.
The child fork then debugs the new process. The parent process is not affected.
Show Follow-fork-mode
Displays the current debugger's response to the fork/vfork call.
Under Linux, if you want to debug the parent and child processes, use the command
Set Detach-on-fork.
Set Detach-on-fork mode
Sets whether gdb detach one of the processes after the fork, or continues to retain control over the two processes.
The on child process (or the parent process, which relies on follow-fork-mode values) is detach and then run independently. This is the default mode.
Off two processes are controlled by GDB. A process (child process or parent process, dependent on follow-fork-mode) is debugged, in addition
One is suspended.
Show Detach-on-fork
Show Detach-on-fork mode
If you choose to set ' Detach-on-fork ' to OFF, GDB will maintain control over all created subroutines (including those created by nesting). You
You can use the Info forks command to display the child processes created in GDB, and then use the Fork command to switch from one process to another.
Info forks
Prints a list of sub-processes that were created under GDB control. This table includes the fork ID, the process ID, and the location of the current process (program counter).
Fork Fork-id
Switches to fork-id the specified process. The parameter fork-id is assigned to fork within GDB, such as the first of the list shown in command ' info forks '
Column.
Process Process-id
Switches to process-id the specified process. The parameter Process-id must be ' info forks ' output.
To end debugging a created process, you can use the Detach Fork command (which allows the process to run independently), or delete (also kill)
Method of the Delete Fork command.
Detach Fork Fork-id
Detach a process specified by the Fork-id identified by GDB and then removed from the fork list. This process will be allowed to continue running independently.
Delete Fork Fork-id
Kills a process specified by the Fork-id identified by GDB and then removes it from the fork list.
If you are debugging a vfork that creates the next exec process, GDB will execute a breakpoint on the new target. If you are in the original program
A breakpoint is set on the main function of the child process, and the same breakpoint is on the main function on the subprocess.
If the child process is executing a vfork call, you cannot debug the child process or the parent process.
If you run GDB's Run command after the EXEC call executes, the new target restarts. To restart the parent process, run the file command, and the parent process can execute the program
A masterpiece parameter.
You can use the catch command to break gdb when the fork,vfork or exec call is made.

4.11 Setting bookmarks for jumps
In some operating systems (currently only on Gnu/linux), GDB can save a snapshot of the state of a program, called a checkpoint, which can then be skipped back.
Jumping back to the checkpoint will undo all changes after the checkpoint. These changes include memory, registers, and even system state (some limitations). This will
Effective and timely return to the status set at the checkpoint.
So you can save a checkpoint if you step into a place where you think you're close to an error. And then, if you walk out of the way,
Too far to miss the critical state, you can go back to the checkpoint and start there, without having to start the program from scratch.
Checkpoints can be helpful in situations where a bug takes a long time or is in a single-step debug.
Debug with Checkpoint/restart Method:
Checkpoint
Saves a snapshot of the current execution state of the debugged program. The checkpoint command does not require parameters, but each checkpoint is assigned a small integer ID, as
The breakpoint logo is the same.
Info checkpoints
Lists checkpoints in the currently debugged session. For each checkpoint, the information appears as follows:
Checkpoint ID
Process ID
Code Address
Source Line, or label
Restart Checkpoint-id
Restarts on the status of the checkpoint number. All program variables, registers, stack frames, and so on are restored to the saved state on the checkpoint. In essence, GDB will
Dial the clock back to the time recorded by the checkpoint.
Note that breakpoints, gdb variables, command history, and so on are not affected by checkpoint resets. Typically, checkpoints only reset the state inside the debugger, without affecting the debugger
The state of the province.
Delete Checkpoint Checkpoint-id
Delete a previously saved checkpoint
Returning to a previously saved checkpoint resets the user state of the program, plus a significant amount of system state, including the file pointer. Resetting does not undo data that has been written to the file, but
is to point the file pointer to the previous civilian, so the previously written data can be overwritten. For files opened in read-only mode, the pointer goes back to its previous location, so
Data can be read again.
Of course, the characters sent to the printer (or other peripherals) are not recoverable, and the data read from other devices (such as the serial device) can be withdrawn from the internal program buffer,
But they cannot be plugged back into the serial pipe and then read them. Similarly, the inside of a file cannot be reset if it is changed.
However, under these constraints, you can go back to the previously saved program state and re-debug – then you can change the process of the event to execute a different path
Debugging.
Finally, when you go back to the checkpoint, some of the internal program states will be different-the process ID of the program. Each checkpoint will have a separate process ID (PID), each with the original
The PID is not the same. If your program saves a local copy of the process ID, there is a potential problem.

4.11.1 the implied benefits of using checkpoints
In some systems (for example, Gnu/linux), for security reasons, the address space of each new process is randomly determined. It's hard, or impossible, at an absolute address.
Set a breakpoint or observer point because the absolute position of a symbol is different every time it executes.
However, a checkpoint is the same copy of a process. So if you create a checkpoint at the entry point of the main function, you can avoid the randomization of the address space
And the symbols will stay in the same position.

Reprint http://zhiwei.li/text/2010/01/gdb%e6%89%8b%e5%86%8c4%e5%9c%a8gdb%e9%87%8c%e8%bf%90%e8%a1%8c%e7%a8%8b%e5%ba%8f/

If you have copyright issues, please contact QQ 858668791

GDB Series four runs the program in GDB

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.