Simvik

Fix: reading a whole register as one field faults

A field extractor works for every field but the full 32-bit one, where its shift is undefined. A medium embedded C problem (Bit manipulation), run and graded…

medium · Bit manipulation · find-the-bug · shifts · undefined-behaviour · masks

Bug report. get_field(reg, lsb, width) extracts width bits starting at bit lsb. It works for every field of the driver's registers, but reading the 32-bit counter register as one field (lsb 0, width 32) stops the program on the simulated chip; on the real one it returned 0 on one compiler and the right value on another. Fix it by changing one line, so that every width from 0 to 32 works.

Starter code

uint32_t get_field(uint32_t reg, unsigned lsb, unsigned width) {
  uint32_t mask = (1u << width) - 1;
  return (reg >> lsb) & mask;
}

Example tests

A byte field, then the whole register

printf("0x%X\n", get_field(0xDEADBEEF, 8, 8));
printf("0x%X\n", get_field(0x12345678, 0, 32));

Expected output:

0xBE
0x12345678

Learn it first

  • Bit manipulation · Masks, shifts, fields and the idioms every register access is built from.

More Bit manipulation problems