0

How can I get the value of IP register in my C program? for example for getting value of AX and BX registers we have pseudo variables _AX and _BX . Is there any pseudo variable for IP register too? or there is any other method? Note: I need value of IP register because it store the offset address of next instruction to be executed?

pradipta
  • 1,718
  • 2
  • 13
  • 24
A.s. Bhullar
  • 2,680
  • 2
  • 26
  • 32

1 Answers1

3

You cannot do it in plain C, since C has no concept of CPU registers. Depending on what compiler you're using, you need to either use:

  • A compiler intrinsic;
  • Inline assembly; or
  • External assembly routine

Check your compiler's documentation to see if there's an intrinsic available. Assuming there's none available, assembly of some sort will be your only option. x86 doesn't have an instruction to directly read the IP register. Instead, you'll need to use something like a call instruction (which stores the next IP on the stack) to get at it.

Here's one way to get the IP on x86 (AT&T syntax):

.globl get_ip
get_ip:
    mov 0(%sp), %ax
    ret

Then in you C code, you can do this:

uint16_t get_ip();
...
uint16_t ip = get_ip();

If your compiler supports inline assembly, then you can use that to write the get_ip function inside your C source code, instead of needing a separate assembly source file. Consult your compiler's documentation on the syntax of inline assembly, if it's available.

The above of course assumes you're working in the 16-bit assembly, which I'm assuming since you mentioned the registers AX, BX, and IP in your question. But if you want this to work for 32-bit code, then of course you need to rename the registers to %esp, %eax, and %eip, and get_eip() would then return a uint32_t instead of uint16_t.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589