'Use of sbb instruction and Carry Flag
I'm studying a question applied in an assembly test and i´m having problems determining what the code is actualy doing. I'll put below what i think it is doind.
I don't understand exatly what the sbb is doing. My guess is that it´s there to trick. I think this, because the Carry Flag is never changed from 0. I´m i wrong? The carry flag is zero before de loop and nothing inside the loop change it. I´m a missing something?
The signature of the function in C is:
char FX (unsigned int N, unsigned int * P1, unsigned int * P2);
And the assembly code (using AT&T format) with my comments is:
FX: pushl %ebp ; stacks ebp
movl %esp, %ebp ; move esp to ebp
pushl %esi ; stacks esi
pushl %edi ; stacks edi
movl 8(%ebp),%ecx ; N
movl 12(%ebp),%esi ; *P1
movl 16(%ebp),%edi ; *P2
cld ; Clear Direction Flag DF = 0
clc ; Clear Carry Flag CF = 0
L1: lodsl ; Load String gets ESI - > EAX = *P1 e P1++(because DF =0)
sbbl (%edi),%eax ; eax = eax - (edi + CF) *P1 = *P1 - (*P2 - 0)
stosl ; Store String saves EAX into EDI *P2 = eax e P2++
loop L1 ; N-- and loops L1 while N > 0
movb $0,%AL ; Clear least significant 2 bytes from EAX without altering flags
adcb %AL,%AL ; AL = AL + AL + CF
popl %edi ; restore edi
popl %esi ; restore esi
popl %ebp ; restore ebp
ret ; return eax
I think this code only copies content from a vector starting in P1 to another vector in P2, but and can't undertand why do i need the sbb, adc instructions, and why a need to worry with carry flag since there is no subtractions or additions.
Thanks for the help!!
Solution 1:[1]
This looks like a function that treats the arguments P1 and P2 as pointers to BigNums of length N and computes their difference, storing it back into P2. It finally returns in the low 8 bits of the return value whether or not the bignum subtraction resulted in a borrow.
Before the loop, the carry flag is set to 0 by the clc instruction. The body of the loop consists of three statements lodsl, sbbl, and stosl. Each time through the loop, the lodsl instruction loads a word from the memory pointed to by esi into eax. The sbbl instruction then subtracts from eax the word from the memory pointed to by edi and also the contents of the carry bit. The first time through the loop, the carry bit will always be 0, so the sbbl works just like a subl would. But the sbbl may also set the carry bit as a result of the subraction. Next time around the loop, that value of the carry bit is used in the sbbl.
The loop is iterated N times, each sbbl using the C flag set by the previous iteration. The net effect is of subtracting two N-word bignums.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
