Simvik

Fix: the bootloader hangs on large chunks

A loop counter is too narrow for the length it counts to. An easy embedded C problem (Protocols, framing and checksums), run and graded in the browser.

easy · Protocols, framing and checksums · find-the-bug · integer-types · loops

Bug report. Firmware updates over the serial bootloader worked with 128-byte chunks. Since the chunk size was raised to 512 bytes, the device hangs on the very first chunk until the watchdog resets it.

send_chunk sends every byte of a chunk with uart_send and returns the 16-bit sum of the bytes. Find the defect and fix it by changing one line.

Starter code

uint16_t send_chunk(const uint8_t *data, uint16_t len) {
  uint16_t sum = 0;
  for (uint8_t i = 0; i < len; i++) {
    uart_send(data[i]);
    sum += data[i];
  }
  return sum;
}

Example tests

An old 100-byte chunk

static uint8_t chunk[512];
for (int i = 0; i < 512; i++) chunk[i] = (uint8_t)i;
uint16_t s = send_chunk(chunk, 100);
printf("%u bytes, sum %u\n", sent, s);

Expected output:

100 bytes, sum 4950

A new 512-byte chunk

static uint8_t chunk[512];
for (int i = 0; i < 512; i++) chunk[i] = (uint8_t)i;
uint16_t s = send_chunk(chunk, 512);
printf("%u bytes, sum %u\n", sent, s);

Expected output:

512 bytes, sum 65280

Learn it first

More Protocols, framing and checksums problems