4 Where Our Code Runs
Winter Semester 2026/2027
Lecture 3 constructed a process from an entry function, owned stack storage, saved CPU context, and lifecycle information. This chapter connects that abstraction to the machines and memory we actually use. It follows four questions raised by students: Where am I working? How do I edit the files that are actually built? Where is the program counter? Where do constants appear in the disassembly? Together they lead to the guiding question: where are our instructions and runtime data, and what must be preserved when execution pauses or is interrupted?
We use the same worker() and permute() from Exercise 2. The aim is to reconstruct and diagnose the existing mechanism before extending it.
4.1 Locate editing, building, and execution
Our setup has three machine roles:
physical host: Linux / macOS / Windows
| hosts the VM; Multipass manages it
v
Ubuntu VM bvs1: our development host
| runs editor, build tools, and QEMU
v
QEMU emulates an RV64 target: CPU + RAM + UART
| target CPU executes RV64 instructions
v
our program / growing BVS1 operating system
The physical host supplies the outer infrastructure. Multipass manages the Ubuntu VM; it is not another machine layer. The VM is the development host for our tools. QEMU runs there as an ordinary Ubuntu process and emulates the target machine.
Both our OS-side control code and the managed process execute on the RV64 target. They do not become Ubuntu programs merely because QEMU runs in Ubuntu. The cross compiler and linker execute in the VM but generate an RV64 ELF for the target ISA.
The complete workflow is:
edit -> save source -> compile/link -> linked ELF
|
QEMU loads the image
|
RV64 instructions execute
Make automates the build recipe. The editor changes source text; the compiler reads the saved file; QEMU receives the resulting ELF. An already running QEMU instance does not automatically acquire a new image when source files are edited or rebuilt.
4.2 Establish a reliable edit–build–run loop
Start on the physical host with:
multipass shell bvs1Inside the VM, locate the existing repository and source file:
cd ~/teaching-bvs1-code
pwd
ls
nano main.cRun make from the repository directory that contains the Makefile. Make reads the Makefile in the current directory, and that Makefile names the source files it compiles. A main.c edited in another directory or another copy of the repository is not this build’s input.
In nano, save with Ctrl-O, Enter, then leave with Ctrl-X. If using Vim, enter Insert mode with i, make the change, press Esc, then save and leave with :wq. The editor handout contains further details. The relevant competence is editing the intended file reliably; the choice of editor is not assessed.
After saving, inspect your change and build:
git diff -- main.c
make
make runUse one small output-label change to connect the saved file to an observable effect. The array’s permutation should remain unchanged if only a label changes. End QEMU with Ctrl-a, release, then x. Restore that intentional label change before continuing.
If an old label appears, diagnose the chain in order:
saved source -> build input -> successful build -> executable -> QEMU run
Was the change saved? Is the saved file the one Make uses as build input? Did the build succeed and produce a new executable? Did a new QEMU session load that executable? Rebuilding repeatedly cannot correct an unsaved buffer or a different repository copy.
4.3 One managed execution can contain several active calls
Exercise 2 uses this entry function:
static void worker(void)
{
char value[] = "BVS1";
permute(value);
uart_puts("process: result: ");
uart_puts(value);
uart_puts("\n");
process_exit(0);
}The local array has five bytes: B, V, S, 1, and the terminating zero byte. It is modifiable character data. The helper receives a pointer to that existing array; passing it does not create another array or another process.
The helper first exchanges positions 0 and 1, prints the intermediate value, calls process_yield(), then exchanges positions 2 and 3. Before yield, both worker() and permute() are still active. The array has become VBS1\0, but its owning worker invocation has not ended.
4.4 Instructions and runtime data have different roles
The linked program places machine instructions in .text. This includes instructions implementing the worker, helper, process API, and OS-side code. Calling a function transfers control to its instructions; it does not copy those instructions onto the stack.
The program counter, pc, identifies the instruction to execute. The stack pointer, sp, selects the current stack position. These are CPU state, not memory sections. A saved return address is an address value that points back into code; its being stored on the stack does not make the pointed-to instructions stack contents.
The stack holds runtime data associated with active calls: saved call information, saved registers, some local variables, and temporaries as needed. The call data of one active call is its stack frame. The labels worker stack frame and permute stack frame describe this runtime data, not the functions’ instructions.
A schematic snapshot after the first swap is:
.text process-owned stack storage
higher addresses
same worker instructions +--------------------------+
same permute instructions | worker: value V B S 1 \0 |
... +--------------------------+
call process_yield | permute call data |
+--------------------------+
lower addresses
The CPU has changed data in the array while executing instructions that remain in .text. A non-inlined helper call uses the same process stack as the worker, with newer call data toward lower addresses. The picture does not prescribe exact offsets, compiler-generated stack frames, or a stack slot for every local value.
4.5 sp, ra, and pc are different kinds of CPU state
sp and ra are the conventional ABI names of the integer registers x2 and x1. Ordinary instructions read and write them like the other general-purpose registers x0–x31. The program counter is also architectural CPU state, but it is not one of these 32 registers. The CPU advances it as it executes, and jumps, branches, calls, and returns change it.
This explains why the Lecture 3 context contains ra, sp, and s0–s11 but no explicit pc. The cooperative context switch happens at an ordinary function-call boundary, so the saved ra already describes the continuation:
saved ra -> restored ra -> ret -> execution continues there
ret sets the program counter to the restored ra. The program counter is therefore not forgotten; the cooperative switch re-establishes it through ra.
Note the distinction this relies on. No saved context contains the live pc, which changes with every instruction. It contains a continuation address: a saved value saying where the execution continues when it is restored. In CP1 that value is ra, and ret turns it back into pc.
4.6 Follow the same execution through yield and resume
When the process yields, the low-level switch saves its continuation, stack position, and required additional registers. The OS context is restored. The CPU’s current pc and sp now describe OS execution, while p.context holds the saved register values for the paused process. The array and suspended call data remain in p.stack.
The next process_run() restores that saved context. Low-level continuation first returns through the suspended yield path. process_yield() then returns to the same permute() invocation, which performs the second swap. The array becomes VB1S\0. The worker does not initialize it again, because no new worker invocation was started.
When the helper returns, the worker prints the result and calls process_exit(0). Exit marks the process FINISHED and returns control to the OS. Old bytes may physically remain after a helper returns or a process exits; that does not keep a call active or authorize another run. Lifecycle state determines whether the process may run again.
| Moment | Array contents | CPU executes |
|---|---|---|
| worker initialized it | BVS1\0 |
process |
| first swap completed | VBS1\0 |
process |
| yielded | VBS1\0, preserved |
OS |
| second swap completed | VB1S\0 |
process |
| process exited | no active array | OS |
Calling entry again restarts the work; restoring a continuation without the matching stack position loses the original call chain; allowing a FINISHED process to run violates its lifecycle. These are different failures of the same model.
4.7 Connect the other memory regions
The section names describe roles in the linked image:
| Region | Role in our example |
|---|---|
.text |
RV64 machine instructions |
.rodata |
constant data, including output labels |
.data |
writable static/global objects with stored initial values, when present |
.bss |
zero-initialized static/global storage, including OS bookkeeping in the inspected library |
| OS stack | runtime data of OS-side calls |
| process stack storage | runtime data of the managed process’s calls |
The output label "process: result: " is constant data, normally placed in .rodata. The initialized local value array is a separate writable object. Its C initializer does not put that array in .rodata: the compiler can provide its initial bytes from constants in instructions or from constant storage. Inspect the actual build rather than assuming a separate BVS1 string must be present in .rodata.
Constants therefore appear in the disassembly in two forms:
- A value small enough to encode inside an instruction appears as an immediate operand, for example in
lioraddi. Larger values may be built by more than one instruction. The four characters ofBVS1can appear together as one 32-bit value: our target uses little-endian byte order, so storing0x31535642produces the bytes0x42 0x56 0x53 0x31at increasing addresses. - In this build, constant output labels are stored in
.rodata. Instructions compute a label’s address, typically with anauipc/addipair thatobjdump -dannotates with the resulting address, and pass it touart_puts().riscv64-unknown-elf-objdump -s -j .rodata build/hello-bvs1.elfshows the bytes stored at that address.
For comparison, a static/global int initialized = 7 typically belongs to .data; a static/global int zeroed initially has value zero and typically belongs to .bss. Static storage lasts for the execution of the program, unlike the local state of a particular call. Neither declaration is needed in the Exercise 2 application merely to fill a diagram.
In the inspected Exercise 2 image, .data is empty. The local value array belongs to neither section: it lives on the process stack while worker() is active. Its .bss contains os_context and current_process from the provided library. A pointer becoming nonzero at runtime does not move its storage to .data. BSS occupies memory even though the ELF does not store all its initial zero bytes as file contents; loading/startup must establish the required initial state.
These roles do not imply that our minimal system enforces read/write permissions or separate address spaces. The course linker script and runtime storage choices determine the layout we are studying.
4.8 The process stack is an array in an object
Exercise 2 declares:
void main(void)
{
struct process p;
/* create, run, inspect state, run again */
/* ... */
}Here p is an automatic object in main()’s OS-stack allocation. The embedded array p.stack is part of that object. It reserves a subregion that becomes the process’s active call stack when sp selects an aligned position inside it.
This gives the process distinct stack storage for its execution without creating another ELF section. While the process runs, OS-side calls are suspended. When the OS regains control, it uses other stack space and leaves p.stack intact. main() remains active throughout, so the process object and its embedded storage remain alive.
If p were instead static/global, its containing storage would be static. The role of its stack array would remain process-owned runtime storage. Therefore “process stack” answers what the memory is used for; the declaration and allocation answer where that memory comes from. In this example no dynamic allocation is required.
4.9 Inspect the file without confusing it with live memory
After a successful Exercise 2 build, run these commands in the VM:
riscv64-unknown-elf-objdump -h build/hello-bvs1.elf
riscv64-unknown-elf-nm -n build/hello-bvs1.elf
riscv64-unknown-elf-objdump -d \
--disassemble=context_switch build/hello-bvs1.elfThe first command lists sections; the second lists symbols by address; the third decodes the selected function’s instructions. In nm, T/t identifies code symbols and B/b identifies BSS-related symbols. A symbol can simply name an address: _stack_top is the linker-defined initial OS-stack address, not a C array declaration. These inspection options are documented in the GNU Binutils manuals.
The commands inspect the ELF on disk. They do not display the running target’s CPU registers or the live contents of the local array. Debugging information can describe local variables, but that is different from a linker symbol or an observation of runtime memory.
The normal build uses -O2. It can inline permute(), meaning it incorporates the helper’s work into the caller instead of retaining a separate call. Local scalar values such as tmp can be kept in registers. The lecture’s separate observation build uses -O0 -g -fno-inline to retain inspectable function boundaries; -g adds debugging information. Exact stack frames and addresses depend on the build. See GCC’s Optimize Options.
4.10 The next requirement: regain control without cooperation
Our current mechanism depends on the process reaching yield or exit. If it runs forever before either operation, our target-side OS continuation cannot run again. Ubuntu can still manage the QEMU process, but that is control at another layer. Terminating QEMU ends the target session rather than implementing target-side process management.
An interrupt signals an event. When enabled, it transfers control to a configured OS handler, allowing the OS to regain control. A future timer interrupt can make control transfer possible without a voluntary yield. This enables preemption: the OS takes control without the process’s cooperation. Scheduling then decides whether to continue the interrupted execution or select another runnable one. Interrupt handling and the scheduling decision are related but distinct steps.
This chapter raises that question without requiring an interrupt implementation for CP1. An arbitrary interruption is not an ordinary C call boundary. The interrupted continuation is not supplied by ra as it is at our cooperative call boundary; ra holds whatever value the interrupted code was using. Once control has transferred into OS entry code, software can no longer recover the interrupted program counter unless the hardware captured it at that moment. It must therefore be preserved explicitly, in dedicated trap state, together with the other registers the interrupted code may be using. The cooperative CP1 register subset is not by itself the full specification of such a mechanism.
4.11 Key ideas
- The Ubuntu VM is our development host; the emulated RV64 machine is the target that executes our program’s instructions.
- Editing, saving, building, and starting a new run are separate steps in one observable workflow.
- Function instructions remain in
.text; stack frames contain runtime data associated with active calls. - A local writable array is distinct from constant data used to initialize it or print an output label.
- Process stack storage is an array in the process object; its role does not prescribe an ELF section or an address space.
- Preserved stack data and saved register context together support continuing the same execution.
- The program counter is CPU state but not a general-purpose register: the cooperative switch re-establishes it through a saved continuation address (
raandret), whereas after an interruption only the hardware can record where to continue. - Lifecycle state determines whether another run is permitted, even if old memory contents remain.
References
- GNU Binutils, objdump and nm.
- GCC, Optimize Options.
- RISC-V International, RISC-V ABIs Specification.
- Arpaci-Dusseau and Arpaci-Dusseau, Operating Systems: Three Easy Pieces.