( One )gdb Debugging principle

This part is transferred from :https://blog.csdn.net/u012658346/article/details/51159971     https://www.cnblogs.com/xsln/p/ptrace.html

gdb The principle of debugging is based on ptrace system call ,ptrace() System calls provide a method , This method makes a program ( Stalker ) Another program can be observed and controlled ( Tracked ) Implementation , And check and change the memory and register of the tracked person . It is mainly used for breakpoint debugging and tracing system calls .

When tracked , The tracked thread is stopped when it receives the signal , Even if that signal is ignored (SIGKILL With the exception of ). The tracer will call waitpid( Or other classes wait system call ) When you receive a notice , The call returns a status value containing the reason why the tracked thread stopped . When the tracked thread stops , Tracking programs can use a variety of ptrace Request to check and edit the tracked thread . Tracers allow the traced thread to continue running , Selectively ignore incoming signals ( You can even send a completely different signal to the tracked thread )

utilize ptrace system call , Can be debugged in the program and gdb Establish a tracking relationship between them . And then send it all to the debugged program ( Tracked thread ) The signal of ( except SIGKILL) Will be gdb to intercept ,gdb According to the intercepted signal , Check the memory address of the debugged program , And control the debugged program to continue to run .

ptrace System call prototype :

long ptrace(enum __ptrace_request request, pid_t pid,void *addr,void *data);

request Main options for parameters :
PTRACE_TRACEME: Called by child process , Indicates that this process will be tracked by its parent process , All the signals delivered to this process , Even if the signal is ignored ( except SIGKILL outside ), Will make it stop , The parent process will pass the wait() I was informed of this .

PTRACE_ATTACH: attach To a specified process , Make it a child of the current process trace , And the behavior of a subprocess is the same as if it had a PTRACE_TRACEME operation . however , It should be noted that , Although the current process becomes the parent of the tracked process , But the child process uses getppid() What will be reached will still be that of its original parent process pid. When you are in gdb Use in attach Command to track a specified process / threading ,gdb It automatically becomes the parent of the change process , The process being tracked uses a PTRACE_TRACEME,gdb It's natural to take over the process .

PTRACE_CONT: Continue running the child process that was stopped before . The specified signal can be delivered to the subprocess at the same time .

gdb Three debugging methods :
1)attach And debug a running process :
Identify the processes that need to be debugged id, function gdb, Input attch pid, Such as :gdb 12345.gdb You will do the following for the specified :ptrace(PTRACE_ATTACH,pid,0,0), Set up yourself and process number as pid The tracing relationship between processes of . It is using PTRACE_ATTACH, Make yourself the parent of the debugged program . use attach Established tracking relationship , You can call ptrace(PTRACE_DETACH,pid,...) To release . Be careful attach The problem of permission in process , Like a non root Permission of the process is not allowed attach To a root In progress .
2) Run and debug a new process , utilize fork+execve Execute the program under test , The child process is executing execve Previous call ptrace(PTRACE_TRACEME), Set up a connection with the parent process (debugger) Tracking relationship of :
function gdb, Through command line arguments or file Specify the target debugger , Such as gdb ./test 
Input run command ,gdb Do the following :
adopt fork() System call creates a new process
Call in the newly created child process ptrace(PTRACE_TRACEME,0,0,0)
Pass in child process execv() The system call loads the executable file specified by the user
3) Remotely debug the newly created process on the target host
gdb Running on debugging machine ,gdbserver Running on target , Communicate through the data format defined between the two

gdb Debugging basis -- The signal

gdb The implementation of debugging is based on the signal , When using the parameter PTRACE_TRACEME or PTRACE_ATTACH Of ptrace After the system call establishes the debugging relationship , Any signal delivered to the target program is first gdb to intercept . therefore gdb The signal can be processed first , And decide whether to deliver the signal to the target program according to the properties of the signal .

. Breakpoint principle :

1)    The realization principle of breakpoint , Is to insert the breakpoint instruction at the specified position , When the debugged program runs to the breakpoint , produce SIGTRAP The signal . The signal is blocked gdb Capture and determine breakpoint hit , When gdb Judge this time SIGTRAP After the breakpoint hit, it will wait for user input for the next processing , Otherwise continue .

2)    Setting principle of breakpoint : Setting breakpoints in programs , It is to save the original instruction of the location first , Then write to that location int 3. When executed int 3 When , Soft interrupt occurred , The kernel issues a SIGTRAP The signal , Of course, this signal will be forwarded to the parent process . Then replace it with the saved instruction int3, Waiting to resume .

3)    Breakpoint hit decision :gdb Store all breakpoints in a linked list , Hit decision is to compare the current stop position of the debugged program with the breakpoint position in the linked list , Look, it's a breakpoint signal , Or irrelevant signals .

4)    Determination of conditional breakpoints : The principle is the same as 3), Just after restoring the instruction at the breakpoint , Add one more step of condition judgment . If the expression is true , The breakpoint is triggered . Because of the need to judge once , Therefore, after adding the conditional breakpoint , Whether or not a conditional breakpoint is triggered , Will affect performance . stay x86 platform , Some hardware supports hardware breakpoints , Do not insert at conditional breakpoints int    3, Instead, insert another instruction , When the program comes to this address , Do not send out int 3 The signal , Instead, compare the contents of a specific register with that of an address , Then decide whether to send or not int 3. therefore , When the location of your breakpoint is frequently “ Pass by ” when , Try to use hardware breakpoints , Will help improve performance .

One step tracking :

next Instruction can realize single step debugging , That is, only one line of statements is executed at a time . A single line of statements may correspond to multiple instructions , When executed next When the command ,gdb Calculate the address of the first instruction corresponding to the next statement , Then control the target program to go to the position to stop .

gdb Debug basic command

( Two )qemu Medium gdbserver

Under normal circumstances, remote debugging needs to be installed with gdbserver Program , and qemu Built in gdbserver modular , Based on this, we can use gdb Realize to qemu Remote debugging of virtual machine ,GDB/GDBSERVER The principle of debugging model is as follows :

stay GDB/GDBSERVER In debug model ,GDBSERVER It's a lightweight GDB The debugger , Act as a debugging agent during debugging . In the course of debugging , Serial port or network is used as communication channel between host and target . On a host computer GDB Use a channel based on ASCII Simple communication protocol based on RSP It is the same as that running on the target machine GDBSERVER To communicate .GDB Send instructions , Such as memory 、 Register reading and writing ,GDBSERVER First bind to the process running the debugged program image , And then wait GDB Data sent , After parsing the data package containing the command, the related processing will be carried out , And then return the result to GDB.

RSP The agreement will GDB/GDBSERVER The content of communication between them is more like packets , The contents of the packet are all used ASCII character . Every packet follows this format :$ < Debugging information >#< Check code >.

As shown in the figure above , The contents of the package will be 16 Code in decimal form (enhex),# The last two digits are the check code , The specific calculation method is to sum all the characters in the data package and then use 256 Mod . And the content of the packet , That is to say RSP Carrier of protocol , Will be gdb Commands received . After receiving the packet, the receiver , Check the packet , If the response is correct “+”, Instead, respond “-”.

RSP The main commands defined in the protocol can be divided into 3 class :

(1) register / Memory read / write command

command g: Read the values of all registers

command G: Write the values of all registers

command P: Write a register

command m: Read a memory unit

command M: Write a memory unit

(2) Program control command

command ?: Report the last signal

command s: Step by step

command c: Carry on

command k: To terminate the program

(3) Other commands

command O: Console output (Console Output )

command E: Error response (Error response)

When the host uses gdb During debugging ,gdb and qemu The built-in gdbserver Use the above model to interact , Thus to qemu Virtual machine debugging . Such as gdb Debugging end sending x/ <n/f/u> <addr> Means read addr The content of , Command book RSP The protocol is encapsulated in packets and sent to the qemu Of gdbserver End ,gdbserver Check the packet after receiving it , After successful verification, parse and return to gdb client .

Turn on gdbserver after , Will wait to come from gdb Connection request for , The default port is 1234,gdb Use ip And ports and gdbserver Connect :

After the connection is established, the gdb_handlesig() wait for stdin From the gdb Instructions , call gdb_read_byte() Parsing user input , And check the data packet , If the verification is correct, call gdb_handle_packet() Conduct gdb Handling of orders .

The following characters are parsed as m when , Indicates to read a memory unit , Call function target_memory_rw_debug() Read the memory unit , The function finally calls. cpu_memory_rw_debug() Read memory content

When the parsing character is g when , Use gdb_read_register Read register information , This function calls a specific CPU Type of callback function :

x86 Use the following function , adopt qemu Maintenance for virtual machine CPUX86State The structure gets the register information of the virtual machine :

Similarly , When inserting a breakpoint :

stay kvm_enabled Under the circumstances , call kvm_insert_breakpoint:

This function inserts breakpoints and finally uses kvm_update_guest_debug towards kvm Update the client's debug state , This function call kvm_invoke_set_guest_debug, Further call kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,&dbg_data->dbg) perform ioctl to kvm Set related exception vectors in ,BP(breakpoint,int3),DB(int 1)( Insert a sentence , The above instructions can be intercepted by setting these two bits in the exception bitmap )

gdb Debugging principle and qemu Medium gdbserver More articles about

  1. GDB Debugging principle ——ptrace system call

    This article was created by the domineering pineapple , Reprint please indicate the source :http://www.cnblogs.com/xsln/p/ptrace.html All about gdb Please click here for the article index Introduction : gdb Basically everyone is using it , Have you ever thought about it ...

  2. gdb Debug a process that is already running

    One . Debug process on server , There is no source code on the server , So you need to upload the source code to the server , To debug and see the source code , Here are the steps : 1. View service progress id:pgrep service name [user@user-MP app]$ pgrep ...

  3. Use gdb Debug the game server

    Preface talk about gdb Importance Generally speaking . carry gdb, The command is used to debug ." command ", Users are almost the same complex words . And it's true , The actual development and debugging must use gdb. Now . majority Linux The system exists in ser ...

  4. gdb Debugging section error and use

    In programming and debugging , There are often paragraph errors , Available at this time gdb debugging . The specific method is to register the segment error signal processing function , Start in the handler gdb. The specific code is as follows : void segv_handler(int no) { ]; ]; FILE ...

  5. ubuntu: qemu+gdb debugging linux kernel Learning notes

    Statement : The content of this note is not my original ,90% From the integration of online data . meanwhile , Because I have just come into contact with qemu & gdbserver remote debug, This article is not even a tutorial , It's just for reference . ---- ...

  6. stay QEMU In the debugging ARM Program 【 turn 】

    from :http://linuxeden.com/html/develop/20100820/104409.html Recently I want to debug a program that runs on QEMU simulation ARM In the system Linux Program . I've had some trouble , because ...

  7. stay qemu Use... In the environment gdb debugging Linux kernel

    brief introduction For user mode processes , utilize gdb Debugging code is a convenient means . But for the kernel state , You can use crash And other tools based on coredump File debugging . In fact, we can also use some means to Linux Kernel code gdb debugging ,qem ...

  8. QEMU+GDB Debugging method

    Debugging two years ago usb/ip Open source projects , I used virtual machine to debug remotely Windows and Linux system kernel , At that time in VMware Workstation Create two virtual machines to debug , There's no record of how to configure debugging , Just in general ...

  9. Linux Cross compile under gdb,gdbserver+gdb The use of and through gdb debugging core file

    Cross compilation gdb and gdbserver 1. download gdb: Download at :http://ftp.gnu.org/gnu/gdb/ According to the general idea , The latest version, the better , So download 7.2 This version . Of course , Nothing is absolute . We use gd ...

Random recommendation

  1. openstack-swift Cloud storage deployment ( Two )

    Next chapter ,swift-proxy and swift-store Installation Let's talk about server allocation first swift-proxy and keystone Deployed in swift-store It's two   Namely 192 ...

  2. linux mint17.2 install fcitx typewriting

    mint17 When I first came out , Have you ever experienced it on a virtual machine . Now I decide to study hard linux, Plus, it's really cute mint, It's installed on the virtual machine mint17.2 Start configuration fcitx typewriting : add to ppa: sudo add-a ...

  3. CodeReview Learning

    Catalog . introduction . Guidelines for code review . Content of code view . regression testing 0. introduction Code view (Code Review) It means that the software developer is completing the code design . To write . Individual or group code reading process after debugging , generation ...

  4. Android_sharePreference_ex1

    xml file : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro ...

  5. openssl Of CRYPTO_set_locking_callback

    openssl It can be used in multithreaded environment , But the premise is to openssl Provide thread lock facilities , adopt CRYPTO_set_locking_callback Set up . In some complex software environments , There may be multiple upper level modules used at the same time o ...

  6. On ListView

    ListView May be Android The most commonly used control in development , But to use it skillfully, you need constant training . Establish a simple ListView 1. In layout file (.xml) Add <ListView> label 2. stay Ma ...

  7. Animation Physics and The Realization Of Animation In Browsers

    Animation Physics Background With the development of computer science technology, people are facing ...

  8. 【Netty】(5) Source code Bootstrap

    [Netty]5 Source code Bootstrap The last one said AbstractBootstrap, It's a foreshadowing for this article . One . summary Bootstrap yes Netty Provides a convenient factory class , We can do it through it ...

  9. Java Copy file in byte stream and character stream

    The process of copying files by byte stream and character stream : 1. Create two flow objects Binding data source and destination 2. Traverse the file to be copied and write it to the new file after copying ( It's just that traversal distinguishes between bytes and characters ) 3. Close resource after access Byte stream copy file : ...

  10. 【learning】 Weighted matroids and greedy

    First .. This article is a summary of matroid knowledge , Some languages are relatively easy to understand , So maybe .. Some of the statements are not so rigorous, probably so ​ Some of the concepts Linearly independent : No quantity in a set of data can be written as a line of the rest ...