Access command line arguments with gdb

I am using linux using gdb version 6.8-debian. I was curious how the main function in the c-program is executed and plays in different places, I found out that the __libc_start_main function is responsible for this. The arguments for __libc_start_main are, among other things: the main address (as we know from c, the path is always set to argv [0]), the next argc, which must be in the ESI register, and the next argv, which must be in ECX.

To play around, I made the following simple cmdargs.c program, which simply returns the first command line argument specified at the beginning:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
    printf("%s: %s\n", "argv[1]", *++argv);
    return EXIT_SUCCESS;
}

Now I start debugging cmdargs and setting a breakpoint on main and __libc_start_main (information from the initial gdb has been deleted):

gdb cmdargs

(gdb) b main
Breakpoint 1 at 0x80483d2
(gdb) b __libc_start_main
Breakpoint 2 at 0xb7f3f5a8
(gdb) r qwerty

2 __libc_start_main argc argv [0]

(gdb) p $esi

(gdb) x/s *($ecx)

, , "qwerty"? , argc argv (?). - , ?

Breakpoint 1, 0x080483d2 in main ()
(gdb) stepi
0x080483d5 in main () 
(gdb) p argc
No symbol "argc" in current context.
(gdb) p argv
No symbol "argv" in current context.
(gdb) 
+3
3

, , .

:

$ gcc -g3 cmdargs.c -o cmdargs

:

$ gdb ./cmdargs
...
Reading symbols from ./cmdargs...done.
(gdb) b main
Breakpoint 1 at 0x400545: file cmdargs.c, line 6.
(gdb) r
Starting program: cmdargs 

Breakpoint 1, main (argc=1, argv=0x7fffffffdc28) at cmdargs.c:6
6       printf("%s: %s\n", "argv[1]", *++argv);
(gdb) p argc
$1 = 1
(gdb) p argv
$2 = (char **) 0x7fffffffdc28
(gdb) p *argv
$3 = 0x7fffffffe00c "/home/jcgonzalez/cmdargs"

, ( ), . Let_Me_Be, array [n], ( [0] -ed) * array @times. , :

(gdb) set args "this is an argument" these are four more 
(gdb) r
Starting program: cmdargs "this is an argument" these are four more

Breakpoint 1, main (argc=6, argv=0x7fffffffdbd8) at cmdargs.c:6
6       printf("%s: %s\n", "argv[1]", *++argv);
(gdb) p argc
$4 = 6
(gdb) p *argv@argc                                    
$5 = {0x7fffffffdfe6 "/home/jcgonzalez/cmdargs", 0x7fffffffdfff "this is an argument", 0x7fffffffe012 "these", 0x7fffffffe017 "are", 0x7fffffffe01b "four", 
  0x7fffffffe020 "more"}
(gdb) p argv[1]
$6 = 0x7fffffffdfff "this is an argument"
(gdb) p argv[2]
$7 = 0x7fffffffe012 "these"
+2

, . GDB , .

(gdb) b main
Breakpoint 1 at 0x400543: file test.c, line 3.
(gdb) r test1 test2
Starting program: /home/simon/a.out test1 test2

Breakpoint 1, main (argc=3, argv=0x7fffffffdca8) at test.c:3
3               puts("blabla");
(gdb) print argc
$1 = 3
(gdb) print argv
$2 = (char **) 0x7fffffffdca8
(gdb) print argv[0]
$3 = 0x7fffffffe120 "/home/simon/a.out"
(gdb) print argv[1]
$4 = 0x7fffffffe132 "test1"
(gdb) print argv[2]
$5 = 0x7fffffffe138 "test2"
(gdb)
+1

-g gcc, , .

+1

Source: https://habr.com/ru/post/1776904/


All Articles