Sample Homework Assignment #9


Overview

This is a sample assignment, which is exactly like all the practice problems posted in this module. Just in case you wanted more practice, here you go.

Solutions

Solutions are available as a plain ASCII file.


Exercise #1: Reverse-engineering

Write a C translation of the NASM program below, sticking to the assembly code as much as possible. Use single-letter variable names for function parameters (e.g., int foo(int x, int y)) and for local variables within function (e.g., int z) instead of using x86 register names (in fact registers should never appear in your translation). It is expected that your C code is much shorter than the assembly code.

Here are requirements for your C program (in addition to it being a correct translation):

Not meeting these requirements will lead to a grade of 0.

Hint: This program outputs the number 304. This information is not useful to write the translation. But it could be useful to make sure your C program also produces the same output (which doesn’t mean it’s a correct translation - since a program with a single printf call would also produce that output).

%include "asm_io.inc"

segment .data
        a       dd      14

segment .bss
        b       resd    1

segment .text
        global  asm_main
asm_main:
        enter   0,0 
        pusha

        push    dword   57
        push    dword   [a]
        call    f
        add     esp, 8
        mov     [b], eax
        inc     dword [b]
        mov     eax, [b]
        call    print_int
        call    print_nl

        popa
        mov     eax, 0 
        leave
        ret

f:
        push    ebp
        mov     ebp, esp

        sub     esp, 4
        mov     eax, [a]
        add     eax, [ebp+8]
        mov     [ebp-4], eax

        cmp     dword [ebp+12], 0
        jnz     nope
        mov     eax, [ebp-4]   
        jmp     endf 
nope:

        mov     eax, [ebp+12]
        shr     eax, 1
        jc      nope2
        inc     dword [ebp-4]
nope2:

        mov     eax, [ebp+12]
        sub     eax, 3
        push    eax
        push    dword [ebp-4]
        call    f
        add     esp, 8  

endf:
        mov esp, ebp
        pop ebp
        ret