Part 9 - Link Register
For a complete table of contents of all the lessons please click below as it will give you a brief of each lesson in addition to the topics it will cover. https://github.com/mytechnotalent/Reverse-Engineering-Tutorial
The Link Register, R14, is used to hold the return address of a function call.
When a BL (branch with link) instruction performs a subroutine call, the link register is set to the subroutine return address. BL jumps to another location in the code and when complete allows a return to the point right after the BL code section. When the subroutine returns, the link register returns the address back to the program counter.
The link register does not require the writes and reads of the memory containing the stack which can save a considerable percentage of execution time with repeated calls of small subroutines.
When BL has executed, the return address which is the address of the next instruction to be executed, is loaded into the LR or R14. When the subroutine has finished, the LR is copied directly to the PC (Program Counter) or R15 and code execution continues where it was prior in the sequential code source.
CODE TIME! Don’t be discouraged if you don’t understand everything in the code example here. It will become clear over the next few lessons.
To compile:
as -o lr_demo.o lr_demo.s ld -o lr_demo lr_demo.o
The simple example I created here is pretty self-explanatory. We start and proceed to the no_return subroutine and proceed to the my_function subroutine then to the wrap_up subroutine and finally exit.
It is necessary that we jump into GDB which is our debugger to see exactly what happens with each step:
As you can see with every step inside the debugger it shows you exactly the progression from no_return to my_function skipping wrap_up until the program counter gets the address from the link register.
Here we see the progression from wrap_up to exit.
This is a fundamental operation when we see next week how the stack operates as the LR is an essential part of this process.
Next week we will dive into the Stack Pointer! Stay tuned!