【发布时间】:2020-01-24 03:52:38
【问题描述】:
在打印出多个单词块(4 个字节)时,gdb 是否会颠倒字节顺序? 如果是这样,那为什么?这和程序如何读取内存有关系吗?
这是一个示例代码来演示我所说的颠倒顺序
// test.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int large = 33825; // 1000 0100 0010 0001
int zero = 0; // 0000 0000 0000 0000
int ten = 10; // 0000 0000 0000 1010
printf("GDB test program\n");
return 0;
}
使用 gdb 编译并运行程序:
$ gcc -z execstack -g -fno-stack-protector test.c -o test
$ gdb test
(gdb) break 9
Breakpoint 1 at 0x8048441: file test.c, line 9.
(gdb) run
Breakpoint 1, main (argc=1, argv=0xbfffeff4) at test.c:9
9 return 0;
(gdb) # get the address of the ten variable (which has the smallest memory address location)
(gdb) print &ten
$2 = (int *) 0xbfffef34
(gdb) # print the first byte of the ten variable
(gdb) x /1tb 0xbfffef34
0xbfffef34: 0000 1010
(gdb) # print the entire memory (4 bytes) allocated for the ten variable (0xbfffef34 - 0xbfffef38)
(gdb) x /1tw 0xbfffef34
0xbfffef34: 0000 0000 0000 0000 0000 0000 0000 1010
(gdb) # Why is "0000 0000" the first octet instead of "0000 1010"
(gdb) # It seems like the print order of the bytes are reversed
(gdb) # Another example
(gdb) # print the entire memory (4 bytes) allocated for the large variable (0xbfffef3c - 0xbfffef3f)
(gdb) x /1tw 0xbfffef3c
0xbfffef3c: 0000 0000 0000 0000 1000 0100 0010 0001
(gdb) x /1tb 0xbfffef3c
0xbfffef3c: 0010 0001
(gdb) x /1tb 0xbfffef3d
0xbfffef3d: 1000 0100
(gdb) x /1tb 0xbfffef3e
0xbfffef3e: 0000 0000
(gdb) x /1tb 0xbfffef3f
0xbfffef3f: 0000 0000
当我打印整个变量时,它会读取我通常如何读取二进制文件(左侧最重要的八位字节)
当我打印同一个变量的第一个八位字节时,它会显示最不重要的八位字节。
GDB 是否重新排列八位字节的顺序以使其更具可读性?这与计算机如何读取内存有什么关系吗?
【问题讨论】:
-
--> "0000 0000" 不是第一个,它是最后一个(内存中的第 4 个)。它在左边并不意味着它是第一个。首先写入最高有效字节。
-
@chux-ReinstateMonica -- 好点子。我想这就是我一直在寻找的答案。二进制是从右到左构造的,我犯了从左到右读取的错误。