Section 4: Assembly game show! #
This section will be a “game show”-style quiz about assembly! The materials here are meant to supplement the slides.
You’ll want to use your assembly cheat sheet for this section!
Mystery program for part 3 #
Here’s the code example for the mystery program in part 3.
Remember from lecture that it is a good idea to work backwards from the ret instruction.
func:
movl $42, -12(%rsp)
movl $0, -4(%rsp)
movl $0, -8(%rsp)
jmp .L2
.L3:
movl -8(%rsp), %eax
addl %eax, -4(%rsp)
addl $1, -8(%rsp)
.L2:
movl -8(%rsp), %eax
cmpl -12(%rsp), %eax
jl .L3
movl -4(%rsp), %eax
ret
main:
movl $0, %eax
call func
ret
.size main, .-main
.ident "GCC: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0"
.section .note.GNU-stack,"",@progbits
QUESTION A. What is the size of the return value of the func function? What type of variable might it return?
QUESTION B. What kind of control flow manipulation (loops, conditionals, etc.) could have been used to generate this assembly code?
QUESTION C. What C program could have generated this assembly code? There are multiple possible C programs that could have done this!
Extra: The Stack #
The following problems are extra materials we have prepared that are relevant to this point in the course, but we don’t plan on covering in section. Depending on how your section goes, we may refer to these problems if we need extra examples. Otherwise, feel free to use these as practice problems!
Consider the following C program. We will draw the layout of the stack at different points in the execution, using the assembly code in q2.s as a reference.
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b) {
int result = a + b;
// *** B ***
return result;
}
int main() {
int result;
long a = 7;
short b = 12;
// *** A ***
result = add(a, b);
// *** C ***
printf("Result of adding %ld and %d is %d.\n", a, b, result);
// *** D ***
return 0;
}
Use the following stack diagram template to help answer the following questions.

QUESTION 2A. What does the call stack look like after the line labeled A is executed (after the local variables are initialized)?
QUESTION 2B. What does the call stack look like after executing the line labeled B (where result is initialized in add)? Make sure to include labels and addresses in the stack diagram.
QUESTION 2C. What does the call stack look like after executing the line labeled C in the diagram (after returning from add, but before calling printf)?
QUESTION 2D. What does the call stack look like after executing the line labeled D in the diagram (after returning from printf, but right before we return from main)?
Acknowledgements: The material for Q3 was originally developed for Harvard’s CS 61 course. We are grateful to Eddie Kohler for allowing us to use the material for CS 300.