CS360 Midterm -- October 18, 2000. Question 1: Answer
and Grading
14 points
The answer
Not too much subtlety here. There were three issues that required
a little thought:
- Where to find argv[1]. To do that, you have to load
[fp+16], add 4 to the value, treat that as an address and
load that address.
- How to push s onto the stack. You initially allocate
20 bytes on the stack. Four of them are for the pointer x.
The rest are the 16 bytes of s. So what is s? It is
the address of the first byte. If you say that x is at address
fp then the first byte of s is going to be at fp-16.
Thus, to push s onto the stack, you need to push the value
fp-16.
- Do we worry about x because it is a pointer?. No.
It's just a 4-byte quantity just like an integer.
Here's the answer:
main:
push #20 / x will be at [fp]. s will be fp-20. Note
/ there's no address at fp-20 -- that is the
/ actual address for s. [fp-20] will be the
/ first byte of s.
ld [fp+16] -> %r0 / Get argv into r0
ld [r0+4] -> %r1 / Get argv[1] into r1
st %r1 -> [sp]-- / Push it on the stack
mv #-16 -> %r0 / s is fp-16. Push that on the stack
add %fp, %r0, -> %r0
st %r0 -> [sp]--
jsr strcpy / call strcpy and pop the args off the stack
pop #8
st %r0 -> [fp] / Store the return value into x
ld [fp] -> %r0 / Push x on the stack
st %r0 -> [sp]--
jsr puts / call puts and pop the arg off the stack
pop #4
ret / return
If you're still confused about why fp-16, see
this link.
Grading
Basic competency points (1 point each):
- Allocating room for x and s on the stack.
- Trying to push argv[1] on the stack.
- Trying to push s on the stack.
- Calling strcpy.
- Popping 8 bytes off the stack.
- Storing the result into x.
- Pushing x onto the stack.
- Calling puts
- Popping 4 bytes off the stack.
- Calling ret
Details (1 point each):
- Accessing x correctly in all cases.
- Accessing argv correctly.
- Accessing argv[1] correctly.
- Accessing s correctly.
Deductions:
- Doing memory-to-memory instructions (e.g. ``ld [fp] -> [sp]--''): -1
- Allocating room for x and s incorrectly: -0.5
- Pushing the arguments in the wrong order: -0.5
- Pushing the arguments without using the stack pointer: -1
- Calling pop #20 instead of pop #8 after strcpy: -1