Assembly code (yasm):
section .data
src db 1,2,3
Each element of src array is 1 byte.
In GDB, how to print the whole array or an element at specified index, e.g print the element with value 2.
(Ok, I'd like to put an answer by myself, with @Michael Petch's permission, to make it more clear for future searcher)
The code & answer are for x86-64 linux system, variables are defined in assembly the .data section.
tmp.asm (yasm)
; yasm assembly program,
; compile: yasm -f elf64 -g dwarf2 tmp.asm && ld tmp.o
; execute: ./a.out
section .data
a db 1
b dw 2
c dd 4
d dq 0x1234567890abcde
arr_a db 1,2,3,4
arr_b dw 1,2,3,4
arr_c dd 1,2,3,4
arr_d dq 1,2,3,0x1234567890abcde
section .text
global _start
_start:
mov rax,1
; exit
mov eax,1
mov ebx,5
int 0x80
In GDB:
p command will treat a variable as 4 byte;x command will treat a variable as 8 byte.So, need different ways to print a number of size 1 / 2 / 4 / 8 bytes.
Examples commands:
p for 4 bytes.
p/x c, print c as 4 byte, this is default.p with cast, for 1 / 2 byte
p/x (char)a, print a as 1 bytep/x (short)b, print b as 2 bytex for 8 bytes
x/x &d, print d as 8 byte, this is default.x for 1 / 2 / 4 bytes
x/bx &a, print a as 1 byte,x/hx &b, print b as 2 byte,x/wx &c, print c as 4 byte,p for array
p/x arr_c@4, print arr_c as array of length 4, contain elements of 4 byte, this is default.p/x (char[4])arr_a, print arr_a as array of length 4, contain elements of 1 byte,p/x (short[4])arr_b, print arr_b as array of length 4, contain elements of 2 byte,p/x (long[4])arr_d, print arr_d as array of length 4, contain elements of 8 byte,p for individual array element
p/x ((long[4])arr_d)[1], treat arr_d as array of length 4, contain elements of 8 byte, and print the element with index 1.Tips:
p could print 8 byte array, but can't print individual 8 byte value correctly (which is not part of array). In that case, use x instead.(This is just tested on my machine, if there is any issue, please feel free to correct it.)
x/s &string if string is a byte array.
p/x (char[3])src? to print the entire array of 3 elements.p/x ((char[4])src)[1]could print individual element of array. If you put it as an answer, I will accept it.