如何在Assembly Langauge X86中检测溢出条件
我有一个任务,我们必须编写两个函数。 还必须使用处理器的条件代码检测溢出条件,并返回0
以指示已遇到错误。 我能够写出这些function。
.file "formula.c" .text .globl _nCr .def _nCr; .scl 2; .type 32; .endef _nCr: pushl %ebp movl %esp, %ebp subl $56, %esp movl 8(%ebp), %eax movl %eax, (%esp) testl %eax, %eax call _factorial movl %eax, -12(%ebp) movl 12(%ebp), %eax addl $1, %eax movl %eax, (%esp) call _factorial movl %eax, -16(%ebp) movl 12(%ebp), %eax notl %eax addl 8(%ebp), %eax movl %eax, (%esp) call _factorial movl %eax, -20(%ebp) movl -16(%ebp), %eax movl %eax, %edx imull -20(%ebp), %edx movl %edx, -28(%ebp) movl -12(%ebp), %eax movl %eax, %edx sarl $31, %edx idivl -28(%ebp) leave ret .globl _factorial .def _factorial; .scl 2; .type 32; .endef _factorial: pushl %ebp movl %esp, %ebp subl $16, %esp movl $1, -8(%ebp) movl $1, -4(%ebp) jmp L3 L4: movl -8(%ebp), %eax imull -4(%ebp), %eax movl %eax, -8(%ebp) addl $1, -4(%ebp) L3: movl -4(%ebp), %eax cmpl 8(%ebp), %eax jle L4 movl -8(%ebp), %eax leave ret .def ___main; .scl 2; .type 32; .endef .section .rdata,"dr" .align 4
这个function基本上是n!/r!(nr)!
。 当数字变大时,溢出发生在阶乘。 我只是不明白我将如何设置溢出条件。
1)您的算术命令是可能设置溢出位的操作
2)“JO”(溢出时跳转)和“JNO”(跳转不溢出)允许分支,具体取决于是否发生溢出
3)你可能只是在“JO”之后将“%eax”设置为0。
4)如果您还不熟悉,那么优秀,优秀的资源:
从头开始编程,Jonathan Bartlett
在x86架构上,当执行算术指令如addl 8(%ebp), %eax
,条件代码在CPU状态字中设置。 有些指令的行为取决于条件代码。
您可以让代码在给定条件下采用备用路径(执行分支)。 x86在Jxx
助记符下有Jxx
条件分支指令: JA, JAE, JB, JBE, JC, JCXZ, ..., JZ
。 例如, JZ
意味着如果为零则跳转:如果指令产生零结果,则设置分支,设置零标志。 JO
在溢出时跳跃。
条件也可以转换为字节数据并存储到寄存器或存储器中。 这对于编译C表达式很有用,例如:
x = (y != 3); /* if (y != 3) x = 1; else x = 0 */
它由SETx
指令组完成,指令组也很多,如条件分支: SETA, SETAE, SETB, ..., SETZ
。 例如,如果零条件为真,SETZ将给定字节设置为1。 例如
seto %bl /* set bottom byte of B register to 1 if overflow flag set */