Bobo loko
Bobo loko

Reputation: 11

How does gdb implement call function

When I use gdb to debug process in arm linux I can use call like call write(123,"abc",3)

How does gdb inject that call into process and recover all?

Upvotes: 1

Views: 569

Answers (1)

Employed Russian
Employed Russian

Reputation: 213526

How does gdb inject that call into process and recover all?

GDB can read and write the inferior (being debugged) process memory using ptrace system call.

So it reads and saves in its own memory some chunk of instructions from inferior (say 100 bytes).

Then it overwrites this chunk with new instructions, which look something like:

r0 = 123
r1 = pointer to "abc"
r2 = 3
BLR write
BKPT

Now GDB saves the current inferior registers, sets ip to point to the chunk of instructions it just wrote, and resumes the inferior.

Inferior executes instructions until it reaches the breakpoint, at which point GDB regains control. It can now look at the return register to know what write returned and print it. GDB now restores the original instructions and original register values, and we are back as if nothing happened.

P.S. This is a general description of how "call function in inferior" works; I do not claim that this is exactly how it works.

There are also complications: if write calls back into the code that GDB overwrote, it wouldn't work. So in reality GDB uses some other mechanism to obtain suitable "scratch area" in the inferior. Also, the "abc" string requires scratch area as well.

Upvotes: 2

Related Questions