Search code examples
arrayscmemoryinitializationgdb

GDB initialize array with contents


I've not found what I am looking for, so I'll formulate my own question.

Consider the C-program below

char heap[<some-static-size>];

void main() {
  <this-code-reads-and-writes-to-heap>
}

I would like to execute this program in gdb, after first having initialized heap. One posibility is that i put the contents of the array in a file, and somehow feed that to gdb. How could I do this easiest? Once main is done, I would like to read the contents of heap and write it to some other file.


Solution

  • The GDB dump and restore commands can be used here. Set breakpoints at main and exit. Use &heap[0] as the start address.

    $ cat heap.c
    char heap[100];
    
    int main() {
        heap[0]++;
    }
    
    $ dd if=/dev/random of=input.bin count=1 ibs=100
    1+0 records in
    0+1 records out
    100 bytes copied, 0.000306025 s, 327 kB/s
    
    $ gdb -q heap
    (gdb) b main
    (gdb) commands
    >restore input.bin binary &heap[0]
    >continue
    >end
    (gdb) b exit
    (gdb) commands
    >dump binary memory output.bin &heap[0] &heap[100]
    >continue
    >end
    (gdb) run
    Breakpoint 1, main () at heap.c:4
    4       heap[0]++;
    Restoring binary file input.bin into memory (0x555555558040 to 0x5555555580a4)
    Breakpoint 2, __GI__exit (status=0) at ../sysdeps/unix/sysv/linux/_exit.c:140
    [Inferior 1 (process 9802) exited normally]
    (gdb) q
    
    $ cmp -l input.bin output.bin
      1  52  53