I would like to store CS (code segment) and IP (instruction pointer) addresses to any of available registers AX, BX, CX or DX. Is it possible somehow to access current CS or IP values?
Asked
Active
Viewed 2,139 times
0
-
Note that call/pop unbalanced the return address predictor stack. If you're writing high-performance 16-bit code for modern CPUs, consider `call` / `mov bx, [bp-something]` / `ret`, where the callee depends on the distance from BP to SP in the caller. (Or consider using x86-64 instead, where RIP-relative addressing modes and LEA solve this problem more efficiently, and you can generally make faster code.) – Peter Cordes Apr 17 '18 at 23:47
2 Answers
5
Yes, CS
is directly accessible. IP
, however, isn't. The usual trick is to do a CALL
instruction which will place it on the stack:
mov dx, cs ; save cs into dx
call next
next:
pop ax ; place ip of "next" into ax, adjust as necessary
Of course this is only needed if the load address is not known.

Jester
- 56,577
- 4
- 81
- 125
-2
Another way to obtain the IP is this:
CALL getIP
getIP:
mov bx, [sp] ; Read the return address into BX.
RET
-
1While this code snippet may solve the question, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) helps to improve the quality of your response. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Stefan Crain Apr 17 '18 at 15:22
-
1`mov bx, [sp]` isn't valid in 16-bit 8086 code. In particular `[sp]` is not a valid memory operand since `sp` can't be used although `bp` can. – Michael Petch Apr 17 '18 at 18:41
-
This avoids unbalancing the return-address predictor stack, so it's faster on modern CPUs. [Reading program counter directly](//stackoverflow.com/q/599968). `mov bx, sp` / `mov bx, [ss:bx]` would do the trick here. – Peter Cordes Apr 17 '18 at 23:42