Can the program counter on Intel CPU's can be read directly (that is without 'tricks') in kernel mode or some other mode?
Thanks :-).
Can the program counter on Intel CPU's can be read directly (that is without 'tricks') in kernel mode or some other mode?
Thanks :-).
No, (E/R)IP cannot be accessed directly. To get it:
call _here
_here: pop eax
; eax now holds the PC.
If you need the address of a specific instruction, usually something like this does the trick:
thisone:
mov (e)ax,thisone
(Note: On some assemblers this might do the wrong thing and read a word from [thisone], but there's usually some syntax for getting the assembler to do the right thing.)
If your code is statically loaded to a specific address, the assembler already knows (if you told it the right starting address) the absolute addresses of all instructions. Dynamically loaded code, say as a part of an application on any modern OS, will get the right address thanks to address relocation done by the dynamic linker (provided the assembler is smart enough to generate the relocation tables, which they usually are).
There is no instruction to directly read the instruction pointer (EIP) on x86. You can get the address of the current instruction being assembled with a little inline assembly:
// GCC inline assembler; for MSVC, syntax is different
uint32_t eip;
__asm__ __volatile__("movl $., %0", : "=r"(eip));
The .
assembler directive gets replaced with the address of the current instruction by the assembler. Note that if you wrap the above snippet in a function call, you'll just get the same address (within that function) every time. If you want a more usable C function, you can instead use some non-inline assembly:
// In a C header file:
uint32_t get_eip(void);
// In a separate assembly (.S) file:
.globl _get_eip
_get_eip:
mov 0(%esp), %eax
ret
This means each time you want to get the instruction pointer, it's slightly less efficient since you need an extra function call. Note that doing it this way does not blow the return address stack (RAS). The return address stack is a separate stack of return addresses used internally by the processor to facilitate branch target prediction for RET instructions.
Every time you have a CALL instruction, the current EIP gets pushed onto the RAS, and every time you have a RET instruction, the RAS is popped, and the top value is used as the branch target prediction for that instruction. If you mess up the RAS (such as by not matching each CALL with a RET, as in Cody's solution), you're going to get a whole bunch of unnecessary branch mispredictions, slowing your program down. This method does not blow the RAS, since it has a matched pair of CALL and RET instructions.