Simvik

Run a tiny program

Execute a small Thumb-like program: moves, adds, compare and conditional branch. A medium embedded C problem (Reading Arm assembly), run and graded in the…

medium · Reading Arm assembly · assembly · registers · flags

Reading assembly means tracking registers and the flags step by step. Write run(prog, n, r), which executes prog (an array of n instructions) on the registers r[0..7] until the program counter runs off the end, and returns the number of instructions executed.

  • MOV rd, #imm: r[rd] = imm
  • ADD rd, rn, rm: r[rd] = r[rn] + r[rm]
  • SUB rd, rn, #imm: r[rd] = r[rn] - imm
  • CMP rn, #imm: sets the Z flag if r[rn] == imm, clears it otherwise (other instructions leave Z alone)
  • BNE target / BEQ target: jump to instruction target if Z is clear / set; B target always jumps

Stop after 10000 instructions in case of an endless loop.

Starter code

int run(const insn_t *prog, int n, int *r) {
  int steps = 0;
  for (int pc = 0; pc < n; pc++, steps++) {
    const insn_t *i = &prog[pc];
    if (i->op == MOV) r[i->rd] = i->imm;
    if (i->op == ADD) r[i->rd] = r[i->rn] + r[i->rm];
    if (i->op == SUB) r[i->rd] = r[i->rn] - i->imm;
  }
  return steps;
}

Example tests

Straight-line code

insn_t p[] = { {MOV, 1, 0, 0, 7}, {MOV, 2, 0, 0, 5}, {ADD, 0, 1, 2, 0} };
show(p, 3, 0);

Expected output:

r0=12 r1=7 r2=5 after 3 instructions

A loop: sum 1 to r0

/* r1 = 0; loop: r1 = r1 + r0; r0 = r0 - 1; cmp r0, #0; bne loop */
insn_t p[] = { {MOV, 1, 0, 0, 0}, {ADD, 1, 1, 0, 0}, {SUB, 0, 0, 0, 1}, {CMP, 0, 0, 0, 0}, {BNE, 0, 0, 0, 1} };
show(p, 5, 4);

Expected output:

r0=0 r1=10 r2=0 after 17 instructions

Learn it first