Memory Graffiti

The questions below are due on Sunday November 22, 2026; 11:59:00 PM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.

1) Attendance

Make sure to scan a QR code from the front and then sign in! You must sign in before proceeding (so resolve any WiFi-related issues now before moving on).

No check in recorded! Lateness Multiplier: 0.5

Did you make sure to scan your QR code? If you did, the box above should be blue and say you checked in. Do not just sign in and leave. We expect you to be working on the lab in lab for your lab session.

2) Drawing and Peeking at Memory

So far, the stack has been something you've reasoned about on paper for the most part: sp goes down, ra gets saved, frames get popped and pushed, you take on the role of a detective for some reason that you're not too clear on but which keeps showing up... Today we're going to look at it directly, on the real chip, while a program is running. This should lean on basically everything we've been doing this term with our C and assembly and memory skills.

We're going to build a drawing program. We've started it, and you're going to finish it up. You'll move a blinking cursor around with the switchboard buttons and draw with it. The display is a window onto a taller world, which scrolls as you move up and down, which is definitely different from how we've used our display before.

Once you get the basic drawing working, you'll add a "flood fill" functionality that fills in whatever shape you've drawn. The flood fill is recursive, and it's the thing we'll spend most of our time poking at: we'll dump the stack while it's running, find the stack frames it builds, follow a return address back into the machine code, and measure exactly how much stack a flood fill uses...right up to the point where it runs out.

2.1) Hardware Setup

Here is our circuit diagram for today's lab (and same for the postlab also for you plan-aheaders). Pretty standard from before, but do pay attention.

Lab 6 schematic.

2.2) The Assignment

The code for today is found here. Download the zip and extract the project folder as you've done previous weeks. Also bring in your gpio_asm.S and 6190.h from last week. The src/ folder has:

  • main.c: the main loop: reads the buttons, moves the cursor, draws the display. You won't need to edit it.
  • world.h / world.c: the world your drawing lives in. You'll write part of world.c.
  • draw.h: the cursor, the display window and the recursive flood fill. You'll write most of this one.
  • floodFill.S: The flood-fill implementation written in assembly. You'll write this.
  • debug.h / debug.S: our stack-peeking tools. You'll write part of debug.S.
  • gpio_asm.S and 6190.h: yours, from last week. These should remain unchanged from previous weeks.

The controls (so you know what to expect) are:

  • Arrow buttons: move the cursor (hold to keep moving).
  • BTNC: pen up / pen down. With the pen down, the cursor blinks fast and moving it draws.
  • BTNF tap: do a flood fill from the cursor. Lift the pen first! (With the pen down, the cursor is always sitting on a lit pixel, and you can't fill a lit pixel.)
  • BTNF hold (1 second): print where the world is in memory, then clear it.
Lab 6 drawing and flood-fill demonstration

3) The World

The drawing you make will live in a world that is larger than our display.

The world is:

  • 32 pixels wide, exactly the width of the display, and...
  • 64 rows tall.
  • Each row's contents are represented by a uint32_t, just like a row of screen_buffer:
#define WORLD_W 32 //found in world.h
#define WORLD_H 64 //found in world.c (for lab6. postlab6 different)

uint32_t world[WORLD_H];   // bit x of world[y] is pixel (x, y)

Just like we've seen in previous weeks with our screenBufer, dimension x grows to the left: bit 0 is the rightmost column of the display. y grows downward (down is positive direction).

Everything else in the program touches the world only through these five functions, declared in world.h:

int  worldHasRow(int y);            // 1 if row y exists (ALREADY WRITTEN)
void worldReset(void);              // clear everything (ALREADY WRITTEN)
void worldDump(void);               // print where the world is in memory (ALREADY WRITTEN)
int  worldGet(int x, int y);        // 1 if pixel (x, y) is lit (YOU WRITE)
void worldSet(int x, int y, int v); // light (v = 1) or clear (v = 0) pixel (x, y) (YOU WRITE)

That might seem like overkill for just an array, but it's going to pay off in the postlab, when we swap in a completely different underlying data structure for our world (a dynamic array rather than the fixed one of this lab uses) and nothing else has to change.

Why have a .h and a .c file? It allows us to more easily separate the existence of functions from their definitions.

To help get a sense of how this is all connected in this lab the diagram below shows how the world is fitting into our view box shown on the display:

The 64-row world, the 8-row window onto it, and the cursor
The world is 64 rows tall, but the display only shows the 8 rows around the cursor! (open full size )

3.0.1) Write worldGet and worldSet

So with this in mind, let's write the two functions below that interact with the world array:

  • worldGet(x, y) returns the value of pixel (x, y) as exactly 0 or 1.

    • Anything outside the world (an x value outside the 0 to 31 range, or a row the worldHasRow function says doesn't exist) returns 1. This allows the edges of the world to act like walls. This will be important when implementing floodFill later on (it'll prevent flood fill from leaking off the sides). Note that for the lab any row in the range of the world buffer will be said to exist (even if it hasn't been drawn on/traversed to yet). This will change for the postlab, so still make sure to use worldHasRow to evaluate whether a row is in bounds for this function.
    • Leave the if (PEEK == PEEK_DRAW && peek_now) block at the top of worldGet alone; we'll use it later on in the lab (it will help us take a look at different memory locations' values during program operation!)
  • worldSet(x, y, v) sets pixel (x, y) to value v (v will be either 0 or 1). Any input (x,y) that is outside the world should be ignored (i.e, should not attempt to modify world state in any way).

Once both functions pass the code checkers, paste them in world.c.

4) Drawing

As mentioned above, we're going to be moving a cursor around the screen. This is how we'll move through our world. We'll represent the cursor as a small struct, defined in draw.h:

struct cursor {
    int x;     // 0..31, x grows leftward
    int y;     // the world row it's on
    int pen;   // 1 = pen down: moving draws and updates world!
};

The attribute x tells us which column the cursor is currently located at. Our cursor's x can take on any value from 0-31 (where 31 is the leftmost column in the world). The attribute y tells us which row in our world the cursor is currently located at. For this lab, our cursor's y can take on any value from 0-63 (because our world has 64 rows, although this will change for the postlab).

Regardless of its y location in the world, the cursor is always displayed on screen row CURSOR_Y (row 4 of the display). When the cursor moves up or down, the world scrolls underneath it so the cursor remains centered vertically. So at any given point, the 8 rows on the screen are world rows c->y - CURSOR_Y through c->y - CURSOR_Y + 7 (where c is a pointer to an instance of our struct cursor). So the 8 rows surrounding the cursor y's location will be displayed.

Near the top or bottom of the world, some of those rows don't exist... and since worldGet returns 1 for them, they'll show up as solid walls. That's the edge of the world. Linked here is a diagram illustrating this concept (the same diagram as pictured earlier in the lab): (open full size).

Write the following functions below:

  • void cursorUpdate(struct cursor *c, int dx, int dy): A function that moves the cursor by (dx, dy), which are each -1, 0 or 1.

    • Make sure cursorUpdate keeps x within the 0 to 31 range (making sure not to wrap around and instead just staying at the boundary limit if trying to go past it), and only move to a new row if worldHasRow says it exists!
    • Then, if the pen is down (actively drawing), color the pixel under the cursor using worldSet.
    • Make sure to use the worldHasRow function to check if a row is in bounds instead of using hardcoded boundaries: if you used hardcoded boundaries your code won't pass the checker.
  • void renderView(const struct cursor *c, int cursor_on): A function that fills screen_buffer[0] to screen_buffer[7] with the 8 world rows around the cursor, using worldGet to determine whether a given screenBuffer pixel should be lit based on the world pixel being rendered at the location.

    • If cursor_on is true, invert the pixel under the cursor (XOR), so the cursor shows up on lit pixels too. main.c calls drawBuffer() for you afterwards, and alternates cursor_on to make it blink. Hint: should you invert the pixel located in screenBuffer or our world buffer?

Check Yourself 1
Why is the pointer to cursor in renderView a const whereas in cursorUpdate it is isn't?

Rememeber both functions above should interact with world only through the worldHasRow, worldGet and worldSet functions! No direct interactions with world!

When finished, add renderView and cursorUpdate to draw.h. You now should be able to move around the world and draw things. Compile, flash, and draw something. Draw at the top and bottom of the screen too, and make sure the world scrolls correctly (scroll up/down/then scroll back.)

At this point you should have this functionality:

  • "Arrow" buttons: move the cursor (hold to keep moving).
  • BTNC: pen up / pen down. With the pen down, the cursor blinks fast, and moving it draws.
  • BTNF hold (1 second): clear and reset the world.

Check Yourself 2
Draw something pretty.

5) Where's the Stack? What's in the Stack?

Now let's start looking at what's running!

You'll see in main.c the following function:

void memoryPrint(uint32_t *addr, int nwords);  // prints nwords words starting at addr

This function is nearly identical to the one we used in lecture 6, just with a few slight formatting differences. memoryPrint will print the contents of memory (one word at a time) starting at the input address and going towards higher addresses, stopping after n words have been printed.

So we can use this function to easily look at memory anywhere in our program. We can do this with variables, instructions, anything. It would be nice to be able to look at the program's stack during run time, so in order to do that we now need two different analysis tools: getStack(n) and getSP().

The getStack(n) procedure below lets us look at the stack. It prints the n words of memory starting at its caller's stack pointer. So when some function calls getStack(32), you see that function's stack, not getStack's.

We've written the printing part for you in C, in main.c:

Your job is the assembly glue around it. getStack should:

  1. Call memoryPrint(addr, nwords), where addr is the value sp had when getStack was called, and nwords is getStack's own argument.
  2. Follow calling convention. In particular, getStack calls another procedure, so think about what that does to ra.

Once it passes, put it in your debug.S. Right below it in that file is a second, even smaller tool we've written for you, getSP(). Don't overwrite getSP.

# C declaration: uint32_t *getSP(void)
getSP:
  mv a0, sp
  ret

getSP() returns its caller's stack pointer. It never moves sp itself (it doesn't call anything, so it doesn't need to affect the stack itself like getStack does), so the value it hands back is exactly the caller's sp.

Now we're all set to look at some stuff.

5.1) A First Look

Throughout the lab we'll be "peeking" at the stack as the code runs. What "peeking" means is that we'll be looking at the state of the stack during some of our function calls by printing stack values starting at sp during that call. We'll have different peeking modes depending on the function we wish to peek during.

All of our stack peeks are controlled by one setting at the top of debug.h:

enum peek_mode {
    PEEK_OFF,      // no dumps (we'll use this when measuring stack use)
    PEEK_DRAW,     // dump worldGet's stack every ~5 s
    PEEK_FILL,     // dump the stack once when floodFill reaches PEEK_FILL_DEPTH (5)
    PEEK_CODE,     // PEEK_FILL's dump, plus floodFill's machine code after the fill
};
static const enum peek_mode PEEK = PEEK_OFF;

static const enum peek_mode PEEK = PEEK_OFF; is the only line you change for any of the peeks in this lab.

For this first part, let's set PEEK to PEEK_DRAW and recompile/flash. What this will do is that every 5 seconds or so, the first worldGet call made while drawing the display calls getStack, so you get a dump of the stack during that call to worldGet (reminder this is coming from this part of the code above):

int worldGet(int x, int y) {
    if (PEEK == PEEK_DRAW && peek_now) {   // stack peek for Checkoff 1
        peek_now = 0;
        getStack(PEEK_DRAW_WORDS);
    }
    //code you wrote above...
}

When that dump happens, at that moment, app_main has called renderView, which has called worldGet. This is important because it is going to guide what we expect.

Open your serial monitor and look through the dump. What do we got in there...? On the ESP32-C3:

  • Addresses starting with 0x3FC are in RAM. The stack lives here, and so do your global variables, like world[] and screen_buffer[].
  • Addresses starting with 0x42 are in a different region in memory associated with where your code lives. A 0x42... value sitting on the stack is almost certainly a saved return address on this particular device.

Find the saved return addresses in your dump. Also find the cursor's x and y: they're in app_main's frame, because app_main owns the struct cursor. Knowing this, also find the pen (and the cursor in general) in memory. Move the cursor, wait for the next dump, and watch them change. Also turn the pen on/off to see how it changes.

Checkoff 1:
Show a staff member your drawing program working: drawing, pen up and down, and scrolling past the top and bottom of the world. Then show a PEEK_DRAW stack dump, and point out a saved return address and where the cursor x and y are as well as the pen. Identify and explain what each stack frame is and from what function.

Before moving on, set PEEK back to PEEK_OFF in debug.h!!

6) The Flood

There's one more drawing functionality we're missing...the flood fill. Pressing BTNF (with the pen up) should flood fill the region under the cursor: this will light every dark pixel you can reach from the cursor by moving up, down, left or right, without crossing a lit pixel. We'll do it recursively, which gives about the simplest flood fill there is:

To flood fill from (x, y): if this pixel is off the screen or already lit, stop. Otherwise, light it, then flood fill from each of its four neighbors.

When you tap BTNF, main.c calls the function fillStart (which we've written for you, and is defined in draw.h) that starts the recursion. It starts the recursion like this: the first input, x, as the cursor's current x location, second input, y, as the cursor's current y location, the third input , top (which determines the maximum y location the floodfills should attempt to fill), set to the world row at the top of the screen so the fill stays inside the 8 rows you can see, and the fourth input depth initialized to 0:

floodFill(c->x, c->y, c->y - CURSOR_Y, 0);

Write floodFill in assembly, in floodFill.S. The starter code below already stops if y isn't one of the rows top through top + VIEW_ROWS - 1, and builds (and tears down) a 20-byte frame for you, with ra, x, y, top and depth at +0, +4, +8, +12 and +16 respectively. You fill in the rest:

  • Don't use any more stack than is already used in the starter!
  • Stop if worldGet(x, y) says the pixel is already lit. (Beyond the left and right edges, worldGet returns 1, so the sides act as walls for free.)
  • Otherwise, light the pixel with worldSet, then call floodFillDebug(depth, sp) with: your depth, and your sp after you've built your frame.
  • Then recurse on the four neighbors in this order: x + 1, x - 1, y + 1, y - 1. Each recursive call will have depth + 1.
  • Note: floodFillDebug is given, in draw.h. It keeps the notes for the investigation later (max_depth, the deepest depth reached, and sp_at_depth[d], your sp at depths 0 through 3), and it's where the PEEK_FILL stack dump happens. It's C, so it follows the calling convention: it can trash any a or t register.

A C equivalent of this behavior is provided below (however note that in C we don't have access to sp like you do in assembly!!!)

void floodFill(int x, int y, int top, int depth) {
    if (y < top || y >= top + VIEW_ROWS){
        return;   // off the screen
    }
    if (worldGet(x, y)){
        return;                    // wall, or already filled
    }
    worldSet(x, y, 1);
    floodFillDebug(depth, sp);   // sp: your sp, after you've built your frame
    floodFill(x + 1, y, top, depth + 1);
    floodFill(x - 1, y, top, depth + 1);
    floodFill(x, y + 1, top, depth + 1);
    floodFill(x, y - 1, top, depth + 1);
}

The starter code is shown below in case you need to start over.

# floodFill
# ARGUMENTS a0: x, a1: y, a2: top, a3: depth
# RETURNS: Nothing
# C declaration: void floodFill(int x, int y, int top, int depth);
floodFill:
    # stop if y is off the screen (given)
    blt a1, a2, return1
    addi t0, a2, 8
    bge a1, t0, return1

    # build the frame (given): ra, x, y, top, depth at +0, +4, +8, +12, +16
    addi sp, sp, -20
    sw ra, 0(sp)
    sw a0, 4(sp)
    sw a1, 8(sp)
    sw a2, 12(sp)
    sw a3, 16(sp)

    # TO-DO: if worldGet(x, y) is 1, skip to return2
    # TO-DO: worldSet(x, y, 1)
    # TO-DO: floodFillDebug(depth, sp)
    # TO-DO: the four recursive calls, in order: x+1, x-1, y+1, y-1, each with depth + 1
    # (worldGet, worldSet, floodFillDebug and floodFill can all trash any a or t register!)

return2:
    # tear down the frame (given)
    lw ra, 0(sp)
    addi sp, sp, 20
return1:
    ret

When it passes, put it in floodFill.S, compile, flash, draw a closed shape, lift the pen, and fill it in! Each fill also prints a short report in your monitor: how deep the recursion went, and sp at the first few depths.

Check Yourself 3
Fill a small closed shape and look at the sp at depth values your board prints. How far apart are they? Does that match the addi sp, sp, ... at the top of your floodFill? If not you've got an issue!

7) How Much Stack Did That Take?

The value max_depth that prints out in the monitor and the known frame size (20) can give you a rough estimate of how much stack a fill uses, but we can actually do better than that, with a trick called stack painting (also sometimes called "watermarking" or "stack-coloring" in other corners of existence). What it is is the following:

  1. Before running the function of interest (floodFill in this case), paint the unused memory below sp with a value you'd recognize, like 0xDEADBEEF or 0x0D06F00D or something obvious. (We can say this region of memory is unused because the stack grows down: nothing lives below sp yet.)
  2. Then...run the function of interest floodFill. Every frame it builds during its initial call and subsequent recursive calls overwrites some of the paint put in place.
  3. After the function call is complete, start at the bottom of the previously painted area and move up (towards sp). The first word that isn't 0xDEADBEEF is marking the deepest point the stack reached.

fillStart already calls the two functions used to paint the stack and measure its usage around the fill. You'll write the two halves below.

Check Yourself 4
Why is it important to start at the bottom of the painted area and move towards sp? Why not start at sp and move until you encounter a 0xDEADBEEF?

So we need to write both of these functions. We'll do them in C:

  • stackPaint(sp): write STACK_PAINT into every word from sp - PAINT_WORDS up to, but not including, sp - PAINT_GAP. PAINT_WORDS is 512, so that's 2 KB below sp. The PAINT_GAP (16 words) leaves alone the memory right under sp, where stackPaint's own frame might be.
  • stackUsed(sp): scan upward from sp - PAINT_WORDS, and return how many bytes below sp the first changed word is, or 0 if nothing changed.

Remember that sp here is a uint32_t *, so sp - 1 is the word just below it: 4 bytes down, not 1.

Once these nasty things are written, put them in draw.h and flash. Now each call to floodFill also reports stack used during the filling action. Fill the same approximate small shape as before.

Compare stack used with (max_depth + 1) × frame size. How do they compare, and why?

8) Following the Return Address

Now let's take apart a dump of the recursion. We do this by going back to debug.h and setting PEEK to PEEK_FILL. Here's one taken with PEEK set to PEEK_FILL while filling a small box.

fillStart's sp: 0x3fc92d10
---- 36 words starting at 0x3fc92c98 ----
0x3fc92c98  (+  0):  0x4200dfb0
0x3fc92c9c  (+  4):  0x00000013
0x3fc92ca0  (+  8):  0x00000005
0x3fc92ca4  (+ 12):  0x00000000
0x3fc92ca8  (+ 16):  0x00000005
0x3fc92cac  (+ 20):  0x4200dfb0
0x3fc92cb0  (+ 24):  0x00000014
0x3fc92cb4  (+ 28):  0x00000005
0x3fc92cb8  (+ 32):  0x00000000
0x3fc92cbc  (+ 36):  0x00000005
0x3fc92cc0  (+ 40):  0x4200dfc8
0x3fc92cc4  (+ 44):  0x00000015
0x3fc92cc8  (+ 48):  0x00000005
0x3fc92ccc  (+ 52):  0x00000000
0x3fc92cd0  (+ 56):  0x00000004
0x3fc92cd4  (+ 60):  0x4200df98
0x3fc92cd8  (+ 64):  0x00000015
0x3fc92cdc  (+ 68):  0x00000004
0x3fc92ce0  (+ 72):  0x00000000
0x3fc92ce4  (+ 76):  0x00000003
0x3fc92ce8  (+ 80):  0x4200df98
0x3fc92cec  (+ 84):  0x00000014
0x3fc92cf0  (+ 88):  0x00000004
0x3fc92cf4  (+ 92):  0x00000000
0x3fc92cf8  (+ 96):  0x00000002
0x3fc92cfc  (+100):  0x4200d9c8
0x3fc92d00  (+104):  0x00000013
0x3fc92d04  (+108):  0x00000004
0x3fc92d08  (+112):  0x00000000
0x3fc92d0c  (+116):  0x00000001
0x3fc92d10  (+120):  0x00000000
0x3fc92d14  (+124):  0x00000001
0x3fc92d18  (+128):  0x0000014b
0x3fc92d1c  (+132):  0x4200dd38
0x3fc92d20  (+136):  0x00000000
0x3fc92d24  (+140):  0x00000013
fill done, max depth 23
  sp at depth 0: 0x3fc92cfc
  sp at depth 1: 0x3fc92ce8
  sp at depth 2: 0x3fc92cd4
  sp at depth 3: 0x3fc92cc0
stack used: 660 bytes below fillStart's sp
(a peek is on, so stack used includes printf's stack)

The dump starts at the sp of the floodFill call at depth 5, so reading down the page you're walking up the stack: depth 5's frame first, then depth 4's, and so on, up to depth 0's frame, which ends right at fillStart's sp. (The last few words, from +120 on, are fillStart's own frame.)

This dump came from one of our boards. Its floodFill uses the same frame as yours: ra, x, y, top and depth at +0, +4, +8, +12 and +16 of a 20-byte frame.

How many bytes is each floodFill stack frame in this dump?

A return address is the address of the instruction after a call: the one execution continues from when the called function returns. Every instruction on our build is 4 bytes, so a call saves (the call's own address) + 4. That means the ra saved in a frame tells you exactly which call created that frame.

In the build that made this dump, floodFill starts at 0x4200df30, and its four recursive calls are at:

Call Address of the call
floodFill(x + 1, y, ...) 0x4200df94
floodFill(x - 1, y, ...) 0x4200dfac
floodFill(x, y + 1, ...) 0x4200dfc4
floodFill(x, y - 1, ...) 0x4200dfdc

The saved x and y make a good check on your answers: compare each frame's x and y with its caller's (the frame just below it in the dump) to see which way the fill stepped.

The frames at depths 1 and 2 both hold return address 0x4200df98. Which of the four recursive calls made them?

The frame at depth 3 holds a different return address, 0x4200dfc8. Which call made it?

The frames at depths 4 and 5 hold a third return address, 0x4200dfb0. Which call made them?

Depth 0's frame holds return address 0x4200d9c8. Where does that point?

9) Your Own Stack

Now you'll do the same thing on your own board. To do so, set PEEK (in debug.h) to PEEK_FILL. Draw a small box (at least 3 wide and 2 tall inside, so the fill has to turn a corner before it gets to depth 5), lift the pen, and fill it.

Your frames are laid out just like the ones you analyzed above. Pick one of your floodFill frames in the dump, and find:

  • its saved return address,
  • the x and y it saved,
  • and which of your four recursive calls to floodFill made it.

Check yourself with the x and y: where they change direction from one frame to the next, the return address should change too (this is because a change in the fill direction means a different line of the floodFill function was used to call itself recursively).

For the checkoff, staff members will want you to: identify each recursive stack frame as well as the initial call to floodFill's stack frame in the dump. Identify what the values in each stack frame represent (y, x, depth, etc...). If you're having trouble with this, remember that the values stored at a given place in the stack frame will be consistent with how values were stored relative to each other in your assembly floodFill implementation.

The staff member checking you off will also want you to identify consecutive frames in the stack dump where you noticed the filling direction changed (and how you identified this by looking at the stack values). So if you find that the direction of the fill is the same accross all 4 recursive calls in your dump, try drawing a new box of an appropriate size and filling from another start location. You can do this randomly until you're able to identify a change in direction for the fill, or by looking at your floodFill implementation to determine where you should start the fill to observe this behavior.

Make notes of all of this since you'll need to show this to a staff member during your checkoff.

9.1) Stack Fatale

Finally....let's intentionally try to run out of stack. Your program's main task has a 3584-byte stack1

  • Using your frame size, roughly how deep can floodFill go before it runs out?
  • An empty screen is 256 pixels. Filling it from the middle goes about 177 levels deep. Will that fit with your current implementation?

Try it: clear the world (hold BTNF), lift the pen, and fill the empty screen. With 20-byte frames it should just barely fit (177 × 20 = 3540 bytes). Now make your frame 24 bytes instead (addi sp, sp, -24 at the top and addi sp, sp, 24 at the bottom; the extra 4 bytes just go unused) and fill the empty screen again. This time it should crash. Read the message your board prints when it crashes. Then find the biggest box you can fill without crashing, and check its max_depth against your prediction. (Its stack used will probably just say "at least 2048 bytes": the paint only covers 2 KB below fillStart's sp, and a fill this deep goes well past that.) Remember to put your frame back to 20 bytes when you're done (done with the checkoff)!

Checkoff 2:
Show a staff member a PEEK_FILL stack dump from your own board. Pick one of your floodFill frames, point out its saved return address and the x and y it saved, and explain which of your recursive calls made it. Then show your prediction for how deep floodFill can go before the stack runs out, the crash, and the biggest box you could fill along with its max_depth.

10) Code Submission

Please submit your world.c, draw.h, floodFill.S and debug.S files in a zip file named None_lab6.zip before asking for a checkoff.

Here's a command that you can run in your terminal:

zip None_lab6.zip src/world.c src/draw.h src/floodFill.S src/debug.S

or for Windows Powershell users,

Compress-Archive -Path src/world.c,src/draw.h,src/floodFill.S,src/debug.S -DestinationPath None_lab6.zip

Submit world.c, draw.h, floodFill.S and debug.S as a zip file: Name the file None_lab6.zip
 No file selected

11) [OPTIONAL] Into the Machine Code

This part is optional and isn't part of either checkoff. If you have time, it's a neat way to see that a return address really does point back at a call in your code.

A return address is an address in your code, and your code is just bytes sitting in memory, like everything else. So we can read it. In the same build as the dump in "Following the Return Address", the 4 bytes at 0x4200dfc4 (the y + 1 call) hold the word 0xf6dff0ef. Let's prove, from the raw bits, that it's a call to floodFill.

Step 1: is it a jal? Write the 32-bit word out in binary. For a jal, the lowest 7 bits (the opcode) are 1101111, and bits 11 to 7 (the destination register) are 00001: register 1, which is ra. That's what makes it a call: it jumps and saves the return address.

Step 2: decode the offset. A jal jumps by an offset from its own address, but the offset's bits are stored shuffled around:

Instruction bits 31 30 to 21 20 19 to 12
become offset bits 20 10 to 1 11 19 to 12

Offset bit 0 is always 0 (instructions are at least 2 bytes apart, so jumps are always even). So the offset, from bit 20 down to bit 0, is:

bit 31, then bits 19 to 12, then bit 20, then bits 30 to 21, then a 0.

That's 21 bits, and bit 20 is the sign: if it's 1, the offset is negative, so subtract 221 (2097152).

Step 3: find the target. The jump goes to (address of the jal) + offset.

The jal at address 0x4200dfc4 holds the word 0xf6dff0ef. What address does it jump to? 0x

Check Yourself 5
The x + 1 call at 0x4200df94 holds a different word, 0xf9dff0ef. Decode it too. It's a different jal, at a different address, with a different offset... but it lands at exactly the same target. Why?

11.1) Your Own Machine Code

Now let's read the call that made one of your own frames, straight out of your own code. Set PEEK to PEEK_CODE. That gives you the same stack dump as PEEK_FILL, plus a code dump (for now it just prints a line telling you to set code_peek_addr). Fill the same small box again, and pick one of your floodFill frames from this new dump.

Stay on PEEK_CODE for this whole part. Changing PEEK changes what code gets compiled in, which moves every address, and return addresses from an earlier build won't point at the right place anymore.

Step 1: find the call. Take the return address from the frame you picked. The call that saved it is the instruction just before it: the 4 bytes at return address − 4. In draw.h, set code_peek_addr to that address, like:

uint32_t code_peek_addr = 0x4200e9fc - 4;   // (your return address) - 4

Compile, flash, and fill the same box again. Your stack dump should show the same return addresses as before (if it doesn't, something besides code_peek_addr changed). After the fill report, you'll now get something like:

---- 16 words starting at 0x4200e9f8 ----
0x4200e9f8  (+  0):  0xf9dff0ef
0x4200e9fc  (+  4):  0x00412503
0x4200ea00  (+  8):  0x00812583
...

That's the machine code of your floodFill, 4 bytes per line, starting at the call. The first word is the one you want.

Step 2: decode it. Decode that first word exactly the way you did 0xf6dff0ef above: check that it's a jal with rd = ra, put the offset bits back in order, and add the offset to the jal's address.

Step 3: check your answer. Set code_peek_addr to the target you got, compile, flash, and fill again. If you got it right, the code dump now starts with the first instructions of your own floodFill: you should recognize your checks on y, then your addi sp, sp, ... (a word ending in 10113), then the sws that fill your frame. You've just proved, from the raw bits, that the call that made your stack frame was floodFill calling itself.


 
Footnotes

1this is the default that the ESP32-C3 allocates for its stack when things are built. It could be changed, but we're not going to. The number might seem weird but 3584 is actually 0xE00 in hex or 1024 * 3.5 (and 1024 bytes is the definition of kilobyte (not 1000 for reference), so this is 3.5 kilobytes of stack....still weird but not as weird as before (click to return to text)