Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify memory contents using GDB?

Tags:

c

linux

memory

gdb

I know that we can use several commands to access and read memory: for example, print, p, x...

But how can I change the contents of memory at any specific location (while debugging in GDB)?

like image 363
bits Avatar asked Jul 22 '10 01:07

bits


People also ask

How do I modify variables in GDB?

Use the set variable (gdb) and the assign (dbx) commands to change the value associated with a variable, memory address, or expression that is accessible according to the scope and visibility rules of the language. The expression can be any expression that is valid in the current context.

How do I change the value of a register in GDB?

To set an individual flag, use its index. E.g., ZF is the 6th bit, so we can set it with: set $ZF = 6 # define a GDB variable: no effect on registers set $eflags |= (1 << $ZF) # set bit 6 in EFLAGS, the ZF bit. The same goes for all other bitwise operations: How do you set, clear, and toggle a single bit?

How do you examine your memory?

You can use the command x (for "examine") to examine memory in any of several formats, independently of your program's data types. Use the x command to examine memory.

How do I create a variable in GDB?

You can create variables in the context of gdb for your convenience, like set $foo = ... and later reference $foo . Obviously such variables are in no way visible to the running code, however. it's not only for inspection. you can change variable values in gdb: stackoverflow.com/questions/3305164/….


2 Answers

The easiest is setting a program variable (see GDB: assignment):

(gdb) l 6       { 7           int i; 8           struct file *f, *ftmp; 9 (gdb) set variable i = 10 (gdb) p i $1 = 10 

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4 

There's more. Read the manual.

like image 146
Nikolai Fetissov Avatar answered Sep 18 '22 07:09

Nikolai Fetissov


As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l 6       { 7           int i; 8           struct file *f, *ftmp; 9 (gdb) set variable i = 10 (gdb) p i $1 = 10  (gdb) p &i $2 = (int *) 0xbfbb0000 (gdb) set *((int *) 0xbfbb0000) = 20 (gdb) p i $3 = 20 

This should work for any valid pointer, and can be cast to any appropriate data type.

like image 32
Andrew Edgecombe Avatar answered Sep 19 '22 07:09

Andrew Edgecombe