Xcode GDB Command List

Source: Internet
Author: User

The lower half of this article is reproduced: But here are some of my own use of skills, combined with the following article, we will have more harvest, here thank the creators.
---------------------

About debugging exception crashes:

The general crash is caused by memory usage errors, either more or less.

Use Xcode's debugging tips to know what caused the crash.

In Xcode , product àedit Scheme à diagnostics will enable Zombie objects and Malloc Stack selection if is a memory release error, gdb prompts the release Dealloc object.

You can then use a breakpoint to narrow the error range, step through the error where it might occur, and gdb will again prompt for release Dealloc object when the error code is executed.

In fact, Xcode embedded GDB, the lldb is GDB!-----------------------http://blog.csdn.net/ch_soft/article/details/7005998about GDB

For most cocoa programmers, the most common debugger is the debug tool that comes with Xcode. In fact, it is a graphical wrapper for GDB. Compared to GDB, graphics bring a lot of convenience, but also lack of some important functions. And in some cases, GDB is more convenient. Therefore, it is necessary to learn about gdb and understand the nature behind the scenes.

GDB can be run through a terminal, or it can invoke commands from the Xcode console. This article will tell you some of GDB's basic commands and tricks through the terminal.

First, let's look at an example:

#import

int main (int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog (@ "Hello, world!");
[Pool release];

return 0;
}


Bad, the program unexpectedly exited normally (==| | | )。 It's not going to work, we have to break him down. So let's add a bug to this applet:

int x = 42;
NSLog ("Hello, world! x =%@ ", x);
Nice This way the program will collapse beautifully:

(GDB) Run

Starting program:/users/mikeash/shell/a.out
Reading symbols for shared libraries. ++++ .... Done .... done.??????

Program received signal exc_bad_access, Could not ACCESS memory.
Reason:13 at address:0x0000000000000000
0x00007fff84f1011c in Objc_msgsend ()
(GDB)

If we were running a program directly in the shell, we would go back to the shell after the crash. But now we're running through GDB, so we're not jumping out now. GDB paused our program, but still kept it in memory, giving us the opportunity to do the debugging.

First, we want to know exactly where it caused the program to crash. GDB has told us through the output just now: The function objc_msgsend is the root of the curse. However, this information is not sufficient because the objc_msgsend is a function in the OBJC Runtime library. We don't know how it's called. Our focus is on our own code.
To know this, we need to get the current process's function call stack in order to backtrack to our own method. At this point we need to use the backtrace command, generally shorthand for BT:

(GDB) bt
#0 0x00007fff84f1011c in Objc_msgsend ()
#1 0x00007fff864ff30b in _cfstringappendformatandargumentsaux ()
#2 0x00007fff864ff27d in _cfstringcreatewithformatandargumentsaux ()
#3 0x00007fff8657e9ef in _cflogvex ()
#4 0x00007fff87beab3e in NSLOGV ()
#5 0x00007fff87beaad6 in NSLog ()
#6 0x0000000100000ed7 in Main () at Test.m:10

Now we can see that in line 10th of TEST.M, the program crashes when it calls the NSLog method. Next we want to look at the details of this call. At this point we need to use the UP command. The up command jumps between the layers of the stack. In this example, our code, Main, is:

(GDB) up 6
#6 0x0000000100000ed7 in Main () at Test.m:10
9NSLog ("Hello, world! x =%@ ", x);
This time, not only the function name, but also the line of code to print out the error. However, we can also use the list (l) command to print out more information:
PS: If you need to go back to the stack list. You can use the down command.

(GDB) L
5
6int Main (int argc, char **argv)
7{
8NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9int x = 42;
10NSLog ("Hello, world! x =%@ ", x);
11[pool release];
12
13return 0;
14}

Ah, the entire code is listed. Although we use the editor to open the test.m file and find the 10th line can also hit the same effect, but obviously no above method more efficient. (Of course no xcode comes with that soon)

OK, now let's take a look at this bug (although we did it ourselves). Obviously, there is a minimum of one @ before formatting the string. We correct it and rerun the program:

(GDB) Run
Starting program:/users/mikeash/shell/a.out
Reading symbols for shared libraries. ++++ .... Done .... done.??????

Program received signal exc_bad_access, Could not ACCESS memory.
Reason:kern_invalid_address at address:0x000000000000002a
0x00007fff84f102b3 in Objc_msgsend_fixup ()
(GDB) bt
#0 0x00007fff84f102b3 in Objc_msgsend_fixup ()
#1 0x0000000000000000 in?? ()

Ah, the program is still crashing. What's more, the stack information doesn't show where the Objc_msgsend_fixup method is called. So we can't find the target code using the above method. At this time, we had to ask for a debugger the most common function: breakpoints.

In GDB, set breakpoints are implemented by the break command. It can be abbreviated to B. There are two ways to determine the location of a breakpoint: pass in a defined symbol, or set the position directly through a file:line pair.
Now let's set a breakpoint at the beginning of the main function:

(GDB) B test.m:8
Breakpoint 1 at 0x100000e8f:file TEST.M, line 8.

Debugger gave us a response telling us that the breakpoint was set successfully, and that the breakpoint was labeled 1. The marking of breakpoints can be useful for sorting breakpoints & deactivating & enabling & deleting, and so on. But we don't need to listen now, we just go ahead and run the program:

(GDB) Run
The program being debugged have been started already.
Start it from the beginning? (Y or N) y
Starting program:/users/mikeash/shell/a.out

Breakpoint 1, Main (argc=1, argv=0x7fff5fbff628) at Test.m:8
8NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
The debugger stopped at the place we expected. Now let's use the next (short N) command to step through the program and see exactly which line it crashed in:

(GDB) n
9int x = 42;
(GDB)
10NSLog (@ "Hello, world! x =%@", x);
(GDB)

Program received signal exc_bad_access, Could not ACCESS memory.
Reason:kern_invalid_address at address:0x000000000000002a
0x00007fff84f102b3 in Objc_msgsend_fixup ()
It is worth noting that I typed only one n command and then hit the carriage return 2 times. The reason for this is that GDB treats any null input as a repetition of the last input command. So here's the equivalent of entering 3 times N.

Now we can see that the place of collapse is still nslog. The reason, of course, is to use%@ to represent the int variable x where the formatted output is. Let's take a closer look at the output: The cause of the crash is the wrong access to the 0x000000000000002a address. The decimal representation of 2a is exactly the value 42--we assign to X. The compiler treats it as an address.

Output value

An important debugging method is to output the values of expressions and variables. In GdB, this is done through the Print command.

(GDB) P x
$ = 42

Append/format after the Print command to format the output. /format is a GDB formatted string that is more useful for formatting characters with x: decimal number; C: Character; A: Address and so on.

(GDB) p/x x
$ = 0x2a

The Print-object Method (abbreviated as PO) is used to output objects in the obj-c. It works by sending a message named Debugdescription to the called object. It's very much like a common description message.

For example, let's output a autorelease pool:

(GDB) PO Pool


This command can not only output an explicitly defined object, but also output the result of an expression. This time we test the signature of the Debugdescription method in NSObject:


The return value is an expression of an object that can be output with the PO command, so what if the return value is a basic type? Obviously, they can be output with the P command. Be careful, however, because GDB does not automatically recognize the type of the return value. So we have to explicitly convert it before the output:

(GDB) p [nsobject instancesrespondtoselector: @selector (doesnotexist)]
Unable to call function ' Objc_msgsend ' at 0x7fff84f100f4:no return type information available.
To call this function anyway, you can cast the return type explicitly (e.g. ' Print (float) fabs (3.0) ')
(GDB) P (char) [NSObject instancesrespondtoselector: @selector (doesnotexist)]
$0 ' 00 '

You may have found that the return value of the Doesnotexist method is bool, and the conversion we made is char. This is because GDB does not recognize types that are defined with typedef. Not just what you define, not even what is defined in the Cocoa framework.

You may have noticed that when you output with P, there is a prefix like "$1=" in front of the output value. They are GDB variables. They can be used in subsequent expressions to refer to the value behind it. In the following example, we open up a piece of memory, set it to zero, and then release it. In this process, we used the GDB variable so that we don't have to copy and paste the address over and over again.

(GDB) p (int *) malloc (4)
$6 = (int *) 0x100105ab0
(GDB) p (void) bzero ($6, 4)
$7 = void
(GDB) P *$6
$8 = 0
(GDB) p (void) free ($6)
$9 = void

We also want to use this technique on objects, but unfortunately the PO command does not store its return value in a variable. So we must first use the P command when we get a new object:

(GDB) p (void *) [[NSObject alloc] init]
$0x100105950 = (void *)
(GDB) PO $

(GDB) p (long) [$ retaincount]
$11 = 1
(GDB) p (void) [$ release]
$ = void

Check memory

Sometimes, just outputting a value does not help us find the error. We need to print out a whole block of memory at once to peek at the global. At this point we need to use the X command.

The format of the X command is X/format address. Where address is simple, it is usually an expression that points to a piece of memory. But the syntax of format is a bit more complicated. It consists of three parts:

The first is the number of blocks to display, the second is the display format (such as x for 16, D for Decimal, and C for characters), and the third is the size of each block. It is noteworthy that the third part, that is, the block size is the character corresponding. Use B, H, w,g respectively to indicate 1, 2, 4, 8 bytes. For example, in hexadecimal, printing 4 4-byte blocks starting with PTR should be written like this:

(gdb) X/4xw ptr

Next, let's take a more practical example. Let's take a look at the contents of the NSObject class:

(GDB) x/4xg (void *) [NSObject class]
0x7fff70adb468:0x00007fff70adb4400x0000000000000000
0x7fff70adb478:0x0000000100105ac00x0000000100104ac0

Then take a look at the contents of a NSObject instance:

(GDB) x/1xg (void *) [nsobject new]
0x100105ba0:0x00007fff70adb468

Now we see that the address of the class is referenced at the beginning of the instance.

Setting variables

Sometimes, the ability to view numerical degrees is slightly weaker, and we also want to be able to modify variables. This is also very simple, just use the SET command:

(GDB) Set x = 43

We can use any expression to assign a value to a variable. For example, create a new object and assign a value:

(gdb) Set obj = (void *) [[NSObject alloc] init]

Breakpoint

We can set breakpoints somewhere in the program so that when the program runs there it pauses and transfers control to the debugger. As mentioned earlier, we use the break command to set breakpoints. Below is a detailed list of how to set the target of a breakpoint:

Symbolname: Specifies a function name for the breakpoint. The breakpoint is then set on the function.
file.c:1234: Sets the breakpoint on one line of the specified file.
-[classname Method:name:]: Set the breakpoint on the OBJC method. Use the + to represent the class method.
*0xdeadbeef: Sets a breakpoint at the specified location in memory. This is not very common, generally in the absence of source debugging when used.

Breakpoints can be switched to use and deactivate by using the Enable command and the Disable command, or they can be completely removed with the delete command. To view an existing breakpoint, use the Info Breakpoints Command (can be abbreviated to info B, or I B).

Alternatively, we can use the IF command to escalate breakpoints to conditional breakpoints. As the name implies, conditional breakpoints only work when the set condition is true. For example, the following statement adds a conditional breakpoint to MyMethod, which is valid only when the parameter equals 5:

(GDB) b-[class myMethod:] if parameter = = 5

Finally, you can attach the GDB command on a breakpoint. This way, when a breakpoint is interrupted, the accompanying command executes automatically. Additional commands use commands Breakpointnumber. GdB then enters the breakpoint command input state.

The breakpoint instruction is a standard GDB sequence of instructions ending with end. For example, we want to output stack information each time NSLog is tuned:

(GDB) B NSLog
Breakpoint 4 at 0x7fff87beaa62
(GDB) commands
Type commands for when Breakpoint 4 are hit, one per line.
End with a line saying just "End".
>bt
>end
  1. Command explanation
  2. Break NUM sets a breakpoint on the specified line.
  3. BT displays all the call stack frames. This command can be used to display the order in which functions are called.
  4. Clear removes breakpoints that are set on a specific source file, on a specific line. Its usage is: Clear filename:num.
  5. Continue continue to execute the program being debugged. The command is used in the program because of processing a signal or breakpoint
  6. Causes the stop run time.
  7. Display EXPR Displays the value of an expression every time the program stops. An expression consists of a variable defined by a program.
  8. The file file loads the specified executable file for debugging.
  9. Help NAME displays assistance information for the specified command.
  10. Info Break Displays the list of current breakpoints, including the number of times the breakpoint was reached.
  11. Info files Displays detailed information about the files being debugged.
  12. Info func Displays all the function names.
  13. Info Local Displays the local variable information in the function.
  14. Info prog shows the execution state of the program being debugged.
  15. Info var displays all the global and static variable names.
  16. Kill terminates the program that is being debugged.
  17. The list displays the source code snippet.
  18. Make to run the Make tool without exiting GDB.
  19. Next executes a line of source code forward without stepping into other functions.
  20. Print expr Displays the value of the expression expr.
  21. Print-object Printing an Object
  22. Print (int) name prints a type
  23. Print-object [artist description] Call a function
  24. Set artist = @"Test" sets the value of the variable
  25. Whatis view the data type of the variable

Xcode GDB Command List

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.