Search code examples
assemblyx86integer-overflowcarryflagsigned-overflow

Checking for overflow and/or carry flags, getting an integer code of which happened


First, I want to point out that this isn't really x86, it's msx88 which is a sort of simplified version of x86 for learning purposes.

I need to make a function that checks for arithmetic errors (carry, overflow) and I know that I can use jo and jc for checking, but the problem is returning back to the point after the check (I don't want to use call, and I am not sure if jumps store IP, so I don't know if I can use ret).

How can I modify my code so that I can execute JO, and if it makes the jump, so that it return to the next instruction after JO (JC)?

ORG 3000H 
ArithmeticError: MOV AX, 0 
JO overflow
JC carry
RET ;Return 
overflow: ADD AX, 1
carry: ADD AX, 2


;If overflow AX=1, if carry AX=2, if overflow and carry AX=3, else AX=0
ORG 2000H
CALL ArithmeticError

END

Solution

  • You should save the flags before any arithmetic. Something like

      MOV AX,0 ; NB not XOR to keep flags intact!
      JNO no_overflow
      PUSHF ; save flags
      INC AX
      POPF ; restore them back for the second check
    no_overflow:
      JNC no_carry
      ADD AX,2
    no_carry:
      ; if AX is zero, we have no error
      TST AX
      JZ out
      CALL ArithmeticError
    out:
      RET