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)?
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.
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?
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.
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/….
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With