GDB is incorrectly presenting global/static C variables
Posted: Tue Dec 15, 2020 2:40 pm
Tl;dr - when using GDB and inspecting global or file static variables with `print var_name` - it will show value from a different memory location.
Example code:
At the mark `print buf` is not the actual `buf`'s memory. Listing the memory I usually able to find it not far from that point. If I print out the address of the memory of the var with `print &buf` I can see the incorrect address.
However all operations are correct. For example setting the variable (`buf[0] = ...`) is correct and I can load it with `... = buf[0]` as well as if I use `printf` from C code, that shows the correct value too - this is why I believe only GDB is confused about it.
Some observations:
- If I read the binary elf I can spot the variables assigned to the address that is not correct (eg 15: 00004100 8 OBJECT LOCAL DEFAULT 5 buf)
- this is the address above that GDB tells me where the variable is
- also this is the address where GDB prints out the memory when I use GDB's print
- looking at the disassembled code - the `movb ...` operations are working with the real and correct address
My setup is the following:
I definitely miss a lot of context here, I wonder where should I start looking for the fix.
Example code:
Code: Select all
/// file1.c
static char buf[16];
// or
// char buf[16];
void foo() {
buf[0] = 'x';
// <- here GDB's `print buf` show garbage
}
However all operations are correct. For example setting the variable (`buf[0] = ...`) is correct and I can load it with `... = buf[0]` as well as if I use `printf` from C code, that shows the correct value too - this is why I believe only GDB is confused about it.
Some observations:
- If I read the binary elf I can spot the variables assigned to the address that is not correct (eg 15: 00004100 8 OBJECT LOCAL DEFAULT 5 buf)
- this is the address above that GDB tells me where the variable is
- also this is the address where GDB prints out the memory when I use GDB's print
- looking at the disassembled code - the `movb ...` operations are working with the real and correct address
My setup is the following:
- GCC flags: -g -Wall -Wextra -ffreestanding -fno-exceptions -pedantic -fno-builtin -fno-stack-protector -nostartfiles -nodefaultlibs -m32
Qemu: qemu-system-i386
GDB is connected through TCP to Qemu
Problem happens in 32bit protected mode (priv 0)
I definitely miss a lot of context here, I wonder where should I start looking for the fix.