Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In gdb, how can I write a string to memory?

Tags:

string

gdb

It is quite straightforward to write ints or hexadecimals to a memory address with gdb:

(gdb) set {int}0x08040000 = 42
(gdb) set {int}0x08040000 = 0xffffffff

But how can I write chars or entire strings in a similarly simple fashion to memory? Right now I have to resort to translating the string to hex and then entering that, which is time consuming.

like image 817
Balz Guenat Avatar asked Oct 21 '13 19:10

Balz Guenat


2 Answers

Say you have the following program:

int main(void){
    char[] person = "Bob";
    char[] p2 = "Alice";

    printf("Hello %s\n");
}

With GDB you could set a breakpoint in main, and change the person's name via:

(gdb) set main::person = { 'S', 'a', 'm', 0x00 }

or more susinctly

(gdb) set main::person = "Sam"

If you want to set memory directly use:

set {char [4]} 0x08040000 = "Ace"

I'm assuming that since you're poking memory with gdb you know what you're doing, so you know about setting the null bytes for strings etc. Keep in mind if you are trying to change values for an array and you try to put in a string that is longer than what was originally allocated, you have a really good chance that you're going to corrupt memory. (example trying to set main::person to "Dilbert" is going to cause problems

like image 126
FuriousGeorge Avatar answered Oct 11 '22 10:10

FuriousGeorge


Use strcpy()

(gdb) p malloc(20)
$3 = (void *) 0x6ce81808
(gdb) p strcpy($3, "my string")
$4 = 1827149832
(gdb) x/s $3
0x6ce81808: "my string"
like image 43
Paul Beusterien Avatar answered Oct 11 '22 11:10

Paul Beusterien