Skip to content

Challenge the Decoder Guarantees

The Course
•
40 min study

test_telemetry.c is about 120 lines, and it makes a strong claim: if it prints Telemetry checks passed, every promise in the brief holds for the inputs it covers. A claim like that is only worth something if you can point to the assertion behind each promise. This lesson walks through the suite in order and maps each block to the contract it defends, then to the mutation it kills. Open the file in the playground at the end and follow along.

The suite, block by block

  1. Allocator probe. The probe starts with fail set, so the first decoder_create must return NULL with zero live blocks. The second create must succeed with one live block after two calls. The call count is saved in allocations. Contract: create fails cleanly and makes one allocation.
  2. Encoder. Invalid records and a 9-byte capacity must be rejected with written still 77 and the output still filled with 0xaa. Then sensor 1, value 25 must encode to exactly the fixture. Contract: validate before writing; bytes match the specification. This guards write_u16; the manifest's byte-order mutation targets read_u16 instead.
  3. Empty feed. NULL with size 0 returns NEED_MORE, consumes 0, leaves the sentinel, and finish reports STREAM_END. Contract: empty input is a valid stream.
  4. Two frames in chunk sizes 1 to 20, through decode_chunks, which asserts that every call makes progress and never exceeds what it was given. Kills "wrong progress count", and also "reverse field byte order": a little-endian read_u16 reads the length 00 04 as 1024, so the very first frame fails its header check.
  5. All 512 partitions of one frame, with exact consumed counts and sentinel checks.
  6. Every truncated prefix must fail at finish and then refuse further input. Kills "accept truncated end".
  7. Every single-byte corruption must be rejected and stay rejected. Kills "ignore checksum".
  8. Metadata changes with repaired checksums, so header rules are proven independently. Kills "accept unsupported version" and "accept unsupported type".
  9. A domain-invalid payload with a correct checksum.
  10. The round-trip grid and the 4095/10000 endpoint.
  11. Allocation accounting. probe.calls == allocations proves that everything above ran without allocating, then destroy must bring live to 0. Kills "omit owned release".

Where is "reset leaves partial count" killed? decoder_create itself calls decoder_reset, so with that mutation a brand-new decoder already believes it holds one byte, and the finish in block 3 reports DECODE_ERROR instead of STREAM_END. Every later block resets too, so several of them would also catch it. A suite only needs one block to kill each mutant, but overlapping coverage means one deleted test rarely lets a mutant survive.

Predict and run

Read the program before pressing Run. Predict the output, then name the extra assertion that proves the existing allocation was released, not just that no new one was made.

Predict before running C
#include <stdio.h>
#include <assert.h>

int main(void) {
    size_t allocations_before = 1, allocations_after = 1;
    assert(allocations_before == allocations_after);
    puts("No feed allocation");
    return 0;
}
Check your prediction
Text
No feed allocation

An unchanged call count shows that feeding did not allocate. It says nothing about release: a destroy that does nothing leaves the count unchanged too. The suite therefore also tracks live blocks and asserts probe.live == 0 after decoder_destroy. The release callback adds a third check, probe->live == 1 && storage != NULL, which fails if destroy runs twice or passes a different pointer.

What the suite does not prove

Precise claims include their limits. The suite covers one fixture's partitions, a grid of valid readings, and single-byte corruptions; it does not cover every possible byte stream. A checksum that passes is not authentication. And the tests exercise behavior, not memory safety: an out-of-bounds read that happens to return a harmless byte passes every assertion. That is why the course's checker can also build the suite with -fsanitize=address,undefined. AddressSanitizer stops on invalid memory access and leaks, and UndefinedBehaviorSanitizer stops on problems such as signed overflow and invalid shifts, the Day 2 hazards. Sanitizers only see code paths that actually run, so they multiply the value of a suite with good coverage rather than replacing it.

Finally, the suite uses assert, which compiles to nothing when NDEBUG is defined. Build the tests without NDEBUG, or the suite will pass by checking nothing.

Practice

Exercise

Your turn

Write const char *audit(size_t created, size_t destroyed, size_t *leaked) that returns "balanced", "leak" with the number of live resources stored in *leaked, or "inconsistent" when more were destroyed than created. It must not compute created - destroyed before checking that it cannot wrap. Print:

Text
created 1, destroyed 1: balanced
created 1, destroyed 0: leak of 1
created 1, destroyed 2: inconsistent
created 3, destroyed 1: leak of 2
Your workspace C
#include <stdio.h>
#include <string.h>

int main(void) {
    const size_t cases[4][2] = {{1, 1}, {1, 0}, {1, 2}, {3, 1}};
    /* Write audit above, then print one line per case. */
    (void)cases;
    return 0;
}
Hint 1: the idea

"More destroyed than created" is the double-free signal, and it must be detected before subtracting, because 1 - 2 on size_t wraps to a huge number that would look like a giant leak.

Hint 2: a first step

Write the three return statements first, with their conditions still to fill in, and decide their order: which case must be ruled out before created - destroyed is safe to compute?

Show one solution
Run the solution C
#include <stdio.h>
#include <string.h>

const char *audit(size_t created, size_t destroyed, size_t *leaked) {
    if (destroyed > created) { return "inconsistent"; }
    *leaked = created - destroyed;
    return *leaked == 0 ? "balanced" : "leak";
}

int main(void) {
    const size_t cases[4][2] = {{1, 1}, {1, 0}, {1, 2}, {3, 1}};
    for (size_t i = 0; i < 4; ++i) {
        size_t leaked = 0;
        const char *result = audit(cases[i][0], cases[i][1], &leaked);
        printf("created %zu, destroyed %zu: %s", cases[i][0], cases[i][1], result);
        if (strcmp(result, "leak") == 0) { printf(" of %zu", leaked); }
        printf("\n");
    }
    return 0;
}
Text
created 1, destroyed 1: balanced
created 1, destroyed 0: leak of 1
created 1, destroyed 2: inconsistent
created 3, destroyed 1: leak of 2

The inconsistent case is the important one. A plain created - destroyed == 0 test would report a double free as a leak of SIZE_MAX, pointing you at the wrong bug. The project's probe gets the same protection from its assert(probe->live == 1 ...) in the release callback. Now run the real suite below and then try a mutation.

Run the complete suite

Complete telemetry checks C
#include "telemetry.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h> typedef struct { size_t calls; size_t live; int fail; } Probe; static void *allocate(void *context, size_t bytes) { Probe *probe = context; ++probe->calls; if (probe->fail) { return NULL; } void *storage = malloc(bytes); if (storage != NULL) { ++probe->live; } return storage; } static void release(void *context, void *storage) { Probe *probe = context; assert(probe->live == 1 && storage != NULL); --probe->live; free(storage); } static const unsigned char fixture[10] = {0x54,1,1,0,4,0,1,0,25,0x74}; static void decode_chunks(Decoder *decoder, const unsigned char *data, size_t size, size_t chunk) { decoder_reset(decoder); size_t offset = 0, frames = 0; while (offset < size) { size_t end = offset + chunk; if (end > size) { end = size; } while (offset < end) { Reading out = {77,88}; FeedResult result = decoder_feed(decoder, data + offset, end - offset, &out); assert(result.consumed > 0 && result.consumed <= end - offset); assert(result.status != DECODE_ERROR); offset += result.consumed; if (result.status == FRAME_READY) { assert(out.sensor == 1 && out.value == 25); ++frames; } else { assert(result.status == NEED_MORE && offset == end); assert(out.sensor == 77 && out.value == 88); } } } assert(frames == size / 10 && decoder_finish(decoder) == STREAM_END); } int main(void) { Probe probe = {0,0,1}; TelemetryAllocator allocator = {allocate, release, &probe}; assert(decoder_create(allocator) == NULL && probe.live == 0); probe.fail = 0; Decoder *decoder = decoder_create(allocator); assert(decoder != NULL && probe.live == 1 && probe.calls == 2); size_t allocations = probe.calls; unsigned char encoded[10]; memset(encoded, 0xaa, sizeof encoded); size_t written = 77; assert(!telemetry_encode((Reading){0,25}, encoded, sizeof encoded, &written)); assert(written == 77); for (size_t i = 0; i < sizeof encoded; ++i) { assert(encoded[i] == 0xaa); } assert(!telemetry_encode((Reading){1,25}, encoded, 9, &written) && written == 77); assert(!telemetry_encode((Reading){4096,25}, encoded, 10, &written)); assert(!telemetry_encode((Reading){1,10001}, encoded, 10, &written)); assert(telemetry_encode((Reading){1,25}, encoded, sizeof encoded, &written)); assert(written == 10 && memcmp(encoded, fixture, 10) == 0); Reading sentinel = {77,88}; FeedResult empty = decoder_feed(decoder, NULL, 0, &sentinel); assert(empty.status == NEED_MORE && empty.consumed == 0); assert(sentinel.sensor == 77 && sentinel.value == 88); assert(decoder_finish(decoder) == STREAM_END); unsigned char stream[20]; memcpy(stream, fixture, 10); memcpy(stream + 10, fixture, 10); for (size_t chunk = 1; chunk <= 20; ++chunk) { decode_chunks(decoder, stream, 20, chunk); } /* Every possible partition of a single 10-byte frame (2^9 cases). */ for (unsigned mask = 0; mask < 512; ++mask) { decoder_reset(decoder); size_t start = 0; for (size_t end = 1; end <= 10; ++end) { if (end == 10 || (mask & (1u << (end - 1))) != 0) { Reading out = {77,88}; FeedResult result = decoder_feed(decoder, fixture + start, end - start, &out); assert(result.consumed == end - start); if (end == 10) { assert(result.status == FRAME_READY && out.sensor == 1 && out.value == 25); } else { assert(result.status == NEED_MORE && out.sensor == 77 && out.value == 88); } start = end; } } assert(decoder_finish(decoder) == STREAM_END); } for (size_t length = 1; length < 10; ++length) { decoder_reset(decoder); Reading out = {77,88}; FeedResult result = decoder_feed(decoder, fixture, length, &out); assert(result.status == NEED_MORE && result.consumed == length); assert(decoder_finish(decoder) == DECODE_ERROR); result = decoder_feed(decoder, fixture, 10, &out); assert(result.status == DECODE_ERROR && result.consumed == 0); assert(out.sensor == 77 && out.value == 88); } for (size_t byte = 0; byte < 10; ++byte) { unsigned char corrupt[10]; memcpy(corrupt, fixture, 10); corrupt[byte] ^= 1; decoder_reset(decoder); Reading out = {77,88}; FeedResult result = decoder_feed(decoder, corrupt, 10, &out); assert(result.status == DECODE_ERROR && result.consumed > 0 && result.consumed <= 10); assert(out.sensor == 77 && out.value == 88); assert(decoder_finish(decoder) == DECODE_ERROR); result = decoder_feed(decoder, fixture, 10, &out); assert(result.status == DECODE_ERROR && result.consumed == 0); } /* Repair checksums after metadata changes to test semantic rejection independently. */ const size_t metadata[] = {0,1,2,4}; for (size_t i = 0; i < sizeof metadata / sizeof metadata[0]; ++i) { unsigned char changed[10]; memcpy(changed, fixture, 10); changed[metadata[i]] ^= 1; changed[9] = 0; for (size_t j = 0; j < 9; ++j) { changed[9] = (unsigned char)(changed[9] + changed[j]); } decoder_reset(decoder); Reading out = {77,88}; assert(decoder_feed(decoder, changed, 10, &out).status == DECODE_ERROR); assert(out.sensor == 77 && out.value == 88); } /* Domain-invalid payload with a correct checksum, rather than checksum-only failure. */ unsigned char invalid[10]; memcpy(invalid, fixture, 10); invalid[6] = 0; invalid[9]--; decoder_reset(decoder); Reading out = {77,88}; assert(decoder_feed(decoder, invalid, 10, &out).status == DECODE_ERROR); assert(out.sensor == 77 && out.value == 88); for (unsigned sensor = 1; sensor <= 4095; sensor += 683) { for (unsigned value = 0; value <= 10000; value += 2500) { decoder_reset(decoder); Reading input = {(uint_least16_t)sensor,(uint_least16_t)value}; assert(telemetry_encode(input, encoded, sizeof encoded, &written)); FeedResult result = decoder_feed(decoder, encoded, written, &out); assert(result.status == FRAME_READY && result.consumed == written); assert(out.sensor == input.sensor && out.value == input.value); } } decoder_reset(decoder); assert(telemetry_encode((Reading){4095,10000}, encoded,10,&written)); assert(decoder_feed(decoder,encoded,10,&out).status == FRAME_READY); assert(out.sensor == 4095 && out.value == 10000); assert(probe.calls == allocations && probe.live == 1); /* feed/reset/finish do not allocate. */ decoder_destroy(decoder); decoder_destroy(NULL); assert(probe.live == 0); puts("Telemetry checks passed"); return 0; } #include "telemetry.h" #include <stdlib.h> #include <string.h> struct Decoder { unsigned char frame[5 + TELEMETRY_PAYLOAD_LIMIT + 1]; size_t used; int failed; TelemetryAllocator allocator; }; static void *default_allocate(void *context, size_t bytes) { (void)context; return malloc(bytes); } static void default_deallocate(void *context, void *storage) { (void)context; free(storage); } TelemetryAllocator telemetry_default_allocator(void) { TelemetryAllocator allocator = {default_allocate, default_deallocate, NULL}; return allocator; } Decoder *decoder_create(TelemetryAllocator allocator) { if (allocator.allocate == NULL || allocator.deallocate == NULL) { return NULL; } Decoder *decoder = allocator.allocate(allocator.context, sizeof *decoder); if (decoder == NULL) { return NULL; } decoder->allocator = allocator; decoder_reset(decoder); return decoder; } void decoder_destroy(Decoder *decoder) { if (decoder != NULL) { decoder->allocator.deallocate(decoder->allocator.context, decoder); } } void decoder_reset(Decoder *decoder) { decoder->used = 0; decoder->failed = 0; } static unsigned long read_u16(const unsigned char *bytes) { return ((unsigned long)bytes[0] << 8) | (unsigned long)bytes[1]; } static void write_u16(unsigned char *bytes, unsigned long value) { bytes[0] = (unsigned char)(value >> 8); bytes[1] = (unsigned char)(value & 255UL); } static unsigned char checksum(const unsigned char *bytes, size_t size) { unsigned char sum = 0; for (size_t i = 0; i < size; ++i) { sum = (unsigned char)(sum + bytes[i]); } return sum; } int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written) { if (out == NULL || written == NULL || capacity < TELEMETRY_FRAME_SIZE || record.sensor < 1 || record.sensor > 4095 || record.value > 10000) { return 0; } unsigned char frame[TELEMETRY_FRAME_SIZE] = {0x54, 1, 1, 0, 4, 0, 0, 0, 0, 0}; write_u16(frame + 5, record.sensor); write_u16(frame + 7, record.value); frame[9] = checksum(frame, 9); memcpy(out, frame, sizeof frame); *written = sizeof frame; return 1; } static FeedResult fail(Decoder *decoder, size_t consumed) { decoder->failed = 1; FeedResult result = {DECODE_ERROR, consumed}; return result; } FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out) { if (decoder->failed) { FeedResult result = {DECODE_ERROR, 0}; return result; } if (out == NULL || (bytes == NULL && size != 0)) { return fail(decoder, 0); } size_t consumed = 0; while (consumed < size) { /* used is bounded by header validation before payload accumulation. */ decoder->frame[decoder->used++] = bytes[consumed++]; if (decoder->used == 1 && decoder->frame[0] != 0x54) { return fail(decoder, consumed); } if (decoder->used == 5) { unsigned long length = read_u16(decoder->frame + 3); if (decoder->frame[1] != 1 || decoder->frame[2] != 1 || length > TELEMETRY_PAYLOAD_LIMIT || length != 4) { return fail(decoder, consumed); } } if (decoder->used == TELEMETRY_FRAME_SIZE) { if (checksum(decoder->frame, 9) != decoder->frame[9]) { return fail(decoder, consumed); } Reading candidate = {(uint_least16_t)read_u16(decoder->frame + 5), (uint_least16_t)read_u16(decoder->frame + 7)}; if (candidate.sensor < 1 || candidate.sensor > 4095 || candidate.value > 10000) { return fail(decoder, consumed); } *out = candidate; decoder->used = 0; FeedResult result = {FRAME_READY, consumed}; return result; } } FeedResult result = {NEED_MORE, consumed}; return result; } DecodeStatus decoder_finish(Decoder *decoder) { if (decoder->failed || decoder->used != 0) { decoder->failed = 1; return DECODE_ERROR; } return STREAM_END; } #ifndef TELEMETRY_H #define TELEMETRY_H #include <limits.h> #include <stddef.h> #include <stdint.h> /* Wire octets require an 8-bit unsigned char. No native struct layout is serialized. */ _Static_assert(CHAR_BIT == 8, "Telemetry format requires 8-bit bytes"); #define TELEMETRY_PAYLOAD_LIMIT 16 #define TELEMETRY_FRAME_SIZE 10 typedef struct { uint_least16_t sensor; uint_least16_t value; } Reading; typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR, STREAM_END } DecodeStatus; typedef struct { DecodeStatus status; size_t consumed; } FeedResult; typedef void *(*AllocateFn)(void *context, size_t bytes); typedef void (*DeallocateFn)(void *context, void *storage); typedef struct { AllocateFn allocate; DeallocateFn deallocate; void *context; } TelemetryAllocator; typedef struct Decoder Decoder; TelemetryAllocator telemetry_default_allocator(void); /* allocator callbacks/context must remain valid until destroy. NULL on failure. One bounded allocation at creation; feed/reset/finish never allocate. */ Decoder *decoder_create(TelemetryAllocator allocator); void decoder_destroy(Decoder *decoder); /* NULL is allowed; other handles exactly once. */ void decoder_reset(Decoder *decoder); /* Requires non-NULL decoder/out; bytes may be NULL only for size zero. Processes at most one frame; caller advances by consumed, then feeds remaining bytes. NEED_MORE consumes all supplied bytes, FRAME_READY consumes through one checksum. Error is sticky until reset. Output changes only on FRAME_READY. Input is borrowed only during this call. Output is a caller-owned value. Decoder, input and output storage must not overlap. */ FeedResult decoder_feed(Decoder *decoder, const unsigned char *bytes, size_t size, Reading *out); /* Check end-of-input: STREAM_END on a clean boundary; partial frame becomes sticky error. A clean finish is a check, not a close: later feed is permitted. */ DecodeStatus decoder_finish(Decoder *decoder); /* Record: sensor 1..4095, value 0..10000. Encoder validates before writing. Requires non-NULL out/written and nonoverlapping record/out/written storage. Failure leaves output bytes and written unchanged. Capacity must be >=10. */ int telemetry_encode(Reading record, unsigned char *out, size_t capacity, size_t *written); #endif
Check your prediction
Text
Telemetry checks passed

Pick one mutation from manifest.json, predict which numbered block above will fail first, then apply it in telemetry.c and run. For "wrong progress count", the first failure is in decode_chunks with chunk size 1, at the assertion on result.consumed. Restore the original line before trying the next one, and do not rely on the exact wording of assertion messages, which differs between C libraries.

Was this article helpful?

Your response is saved on this device.