Categories
How-To Uncategorized

Fun With GDB, Gnu’s Debugger

Here’s a pretty compact version of strcmp:

int bstrcmp(char *s1,char *s2) {
   while(*s1 == *s2++) {
      if(*s1++ == 0){ return 0; }
   }
   return (*(unsigned char *)s1 - *(unsigned char*)--s2);
}

The source that I used for compiling and calling this version of strcmp is here.

Compile that code using:
gcc -o strcmp -g strcmp.c

Fire up the debugger using:
gdb strcmp

You’ll get the gdb prompt:
(gdb)

Set a break point at the start:
b main

The debugger will echo something like:
Breakpoint 1 at 0x80483d5: file strcmp.c, line 6.
(gdb)

Then run the program:
run

The debugger will print out something like:
Starting program: /home/somedude/bin/strcmp

Breakpoint 1, main () at strcmp.c:6
6 {
(gdb)

If you type n a few times, you’ll eventually get to some variable assignments.

(gdb) n
8	char s1[] = "better";
(gdb) n
9	char s2[] = "better than"; /* than this";*/
(gdb) n
11	int i_result = 0;
(gdb) n
13	i_result = bstrcmp(s1,s2);

If you want to the values of these variables type:
p i_result

You get back:
(gdb) p i_result
$1 = 0

To step into a function, type s:

(gdb) s
bstrcmp (s1=0xbf86b469 "better", s2=0xbf86b474 "better than") at strcmp.c:26
26		while(*s1 == *s2++) { 
(gdb) n
27			if(*s1++ == 0){ return 0; } 
(gdb) n
26		while(*s1 == *s2++) { 
(gdb) n
27			if(*s1++ == 0){ return 0; } 
(gdb) n
26		while(*s1 == *s2++) { 
(gdb) 

At this point you can type things like:
p s1
p *s1
p s2
p *s2

And you’ll get back the value of the pointers and what’s in memory.

Next time we’ll go over how to do this with PHP running single threaded on debug mode on Apache.

Leave a Reply

Your email address will not be published. Required fields are marked *