Example Assembly Problems
Problem 1:
Consider the following pairs of C functions and assembly code. Fill in the missing instructions in theassembly code (one instruction per a blank). Your answers should be syntactically correct assembly.
int goose(){return -4;}goose:pushl %ebpmovl %esp, %ebp ___________________________popl %ebpretint cow(int a, int b){return a - b;}cow:pushl %ebpmovl %esp, %ebpmovl 8(%ebp), %eax ___________________________popl %ebpretint pig(int a){return a*3;}pig:pushl %ebpmovl %esp, %ebpmovl 8(%ebp), %eaxleal _______________________popl %ebpret
Page 1 of 17
 
int sheep(int c){if(c < 0)return 1;elsereturn 0;}sheep:pushl %ebpmovl %esp, %ebpmovl 8(%ebp), %eax ___________________________popl %ebpretint duck(int a){if(sheep(a))return -a;elsereturn a;}duck:pushl %ebpmovl %esp, %ebppushl %ebxmovl 8(%ebp), %ebx ___________________________call sheepmovl %ebx, %edx ___________________________je .L6negl %edx.L6:movl %edx, %eaxaddl $4, %esppopl %ebxpopl %ebpret
Page 2 of 17
 
Problem 2:
This problem tests your understanding of IA32 condition codes.A. Consider the instruction:
cmpl
a
,
b
Write in the values (0 if clear, 1 if set) of the condition flags if this instruction is executed with thegiven values of 
a
and
b
.
a b
Zero Flag (ZF) Sign Flag (SF) Carry Flag (CF) Overflow Flag (OF)-4 0xfffffffc4 0xfffffffc-1 12 0x800000000x7fffffff 0x800000000x80000000 0x7ffffff1 0x7ffffff0x80000000 0x800000000x7fffffff 0xfffffffB. On an IA32 architecture, compare and test instructions aren’t the only instructions which set thecondition codes and conditional branches aren’t the only instructions which read the condition codes.Specifically, the
add
instruction sets the condition codes based on the result and the add with carry in-struction (
adc
) computes the sum of its two operands and the carry flag. That is,
adcl %edx,%eax
computes
eax = eax + edx + CF
. Briefly describe a specific instance where the compiler canmake use of this combination of instructions.Page 3 of 17
 
Problem 3:
Consider the following C functions and assembly code:
int fun1(int i, int j){if(i+3 != j)return i+3;elsereturn j*16;}int fun2(int i, int j){if(i+3 != (unsigned)j)return i;elsereturn j*4;}int fun3(int i, int j){if(i+3 <= (unsigned)j)return i;elsereturn j>>2;}pushl %ebpmovl %esp, %ebpmovl 8(%ebp), %eaxmovl 12(%ebp), %ecxleal 3(%eax), %edxcmpl %ecx, %edxjne .L4leal 0(,%ecx,4), %eax.L4:popl %ebpret
Which of the functions compiled into the assembly code shown?Page 4 of 17
of 17