Skip to content

A Checked Byte Cursor

The Course
•
40 min study

A decoder reads many fields in sequence: one octet for magic, one for version, two for length, and so on. Writing bytes[3] and bytes[4] by hand works until the input is shorter than you assumed. Then bytes[4] reads past the end of the array, which is undefined behavior. In a program that reads network input, it is also the root cause of many real-world memory disclosure bugs: the decoder happily reports bytes that belonged to some other object.

A cursor removes the hand-counted offsets. It holds three things: a borrowed pointer, the number of valid bytes, and the current position. Every read goes through a function that checks that enough bytes remain, reads them, and only then advances. The contract has one more clause that is easy to forget: a rejected read changes nothing. Position and output both stay as they were, so the caller can report the failure, wait for more input, or try a different interpretation without first undoing a half-finished read.

Predict and run

Read the program before pressing Run. Write down both lines of output and say which statement produces each.

Predict before running C
#include <stdio.h>

int read_field(const unsigned char *bytes, size_t size, size_t *position, unsigned long *out) {
    if (*position > size || size - *position < 2) { return 0; }
    *out = ((unsigned long)bytes[*position] << 8) | bytes[*position + 1];
    *position += 2;
    return 1;
}

int main(void) {
    unsigned char bytes[2] = {1,2};
    size_t position = 0;
    unsigned long value = 77;
    printf("%d\n", read_field(bytes,2,&position,&value));
    printf("%zu %lu\n", position,value);
    return 0;
}
Check your prediction
Text
1
2 258

The guard is the Day 2 bounds pattern: first prove the position is not past the end, then compare the remaining space with the request. Two bytes remain, so the read succeeds, stores 258 and advances to position 2. Now change the size argument to 1 and predict again. The guard fails, the function returns 0, and the second line prints 0 77: the sentinel 77 proves the output was never written.

Check, read, then advance

The order of the three steps is the whole design. Here is a version that gets it wrong in two ways:

C
int read_field_wrong(const unsigned char *bytes, size_t size, size_t *position, unsigned long *out) {
    *position += 2;                                   /* advances before checking */
    if (*position > size) { return 0; }
    *out = ((unsigned long)bytes[*position - 2] << 8) | bytes[*position - 1];
    return 1;
}

On a one-byte input it returns 0, which looks correct, but the position is now 2, past the end of the data. The next read starts from a broken state. And because it advances by adding, a position near SIZE_MAX would wrap around to a small number and pass the check. The correct order keeps the state valid at every step: nothing moves until the read is known to be in bounds.

Read a sequence and stop at the first short field

A cursor struct bundles the pointer, size and position so each read function needs only one argument for the input. The program below reads a header from a complete buffer and from one that is cut off in the middle of the length field:

A cursor over a truncated header C
#include <stdio.h>

typedef struct { const unsigned char *bytes; size_t size; size_t position; } Cursor;

static int take_u8(Cursor *c, unsigned *out) {
    if (c->position >= c->size) { return 0; }
    *out = c->bytes[c->position++];
    return 1;
}
static int take_be16(Cursor *c, unsigned long *out) {
    if (c->position > c->size || c->size - c->position < 2) { return 0; }
    *out = ((unsigned long)c->bytes[c->position] << 8) | c->bytes[c->position + 1];
    c->position += 2;
    return 1;
}

static void parse(const char *name, const unsigned char *bytes, size_t size) {
    Cursor c = {bytes, size, 0};
    unsigned magic = 0, version = 0, type = 0;
    unsigned long length = 0;
    if (!take_u8(&c, &magic) || !take_u8(&c, &version) || !take_u8(&c, &type)) {
        printf("%s: short before length, position %zu\n", name, c.position);
    } else if (!take_be16(&c, &length)) {
        printf("%s: short at length, position %zu\n", name, c.position);
    } else {
        printf("%s: magic %02X, length %lu, position %zu\n", name, magic, length, c.position);
    }
    (void)version; (void)type;
}

int main(void) {
    const unsigned char header[5] = {0x54, 1, 1, 0, 4};
    parse("full", header, 5);
    parse("cut", header, 4);
    return 0;
}
Text
full: magic 54, length 4, position 5
cut: short at length, position 3

The cut input had one of the two length bytes. take_be16 refused it and left the position at 3, the start of the field it could not read. That is precisely the information a streaming decoder needs: it can keep the three valid bytes, wait for more input, and resume at the right offset.

Where this cursor goes next

The cursor here assumes the whole frame is in one buffer, which is not true for a stream. Day 4's decoder therefore keeps its own bounded internal buffer and copies bytes into it as they arrive, while the public decoder_feed tells its caller how much input it consumed. The same three rules carry over: pointer plus length rather than a terminator, a bounds check before every read however small, and no published change on a rejected read.

Practice

Exercise

Your turn

Many formats carry variable-length fields as a length prefix: one octet n, then n octets of data. Write int take_slice(Cursor *c, const unsigned char **start, size_t *length) that reads such a field without copying it: on success, *start points at the data inside the cursor's input, *length is n, and the cursor moves past the whole field. The all-or-nothing contract now covers two reads: if the data is shorter than its prefix says, the cursor must not move at all, not even past the length octet, so a caller can retry when more input arrives. The starter's attempt helper prints each result (%.*s prints exactly length characters, since the slice has no terminator). It must print:

Text
first: ok "abc", position 4
second, 1 of 2 bytes: failed, position 4
second, after more input: ok "xy", position 7
at end: failed, position 7
Your workspace C
#include <stdio.h>

typedef struct { const unsigned char *bytes; size_t size; size_t position; } Cursor;

/* Write take_slice here. */

static void attempt(Cursor *c, const char *label) {
    const unsigned char *start = NULL;
    size_t length = 0;
    if (take_slice(c, &start, &length)) {
        printf("%s: ok \"%.*s\", position %zu\n", label, (int)length, (const char *)start, c->position);
    } else {
        printf("%s: failed, position %zu\n", label, c->position);
    }
}

int main(void) {
    const unsigned char input[7] = {3, 'a', 'b', 'c', 2, 'x', 'y'};
    Cursor c = {input, 6, 0};
    attempt(&c, "first");
    attempt(&c, "second, 1 of 2 bytes");
    c.size = 7;
    attempt(&c, "second, after more input");
    attempt(&c, "at end");
    return 0;
}
Hint 1: the idea

Read the prefix into a local first, and work out where the data would start, without touching c->position. Only when both the prefix and all n data octets are known to be inside the input does anything get published.

Hint 2: a first step

Write the version that reads the prefix with take_u8-style code (moving the position), then checks the data. Run it: the second line says position 5, not 4. That one octet of drift is what would make a retry read x as a length. Rework the function so the second line keeps position 4.

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

typedef struct { const unsigned char *bytes; size_t size; size_t position; } Cursor;

/* Reads a one-octet length n, then borrows the n octets after it.
   On success *start points into the cursor's input (no copy) and the
   cursor moves past the slice. On failure nothing moves, not even
   past the length octet, and *start and *length are unchanged. */
static int take_slice(Cursor *c, const unsigned char **start, size_t *length) {
    if (c->position >= c->size) { return 0; }
    size_t n = c->bytes[c->position];
    size_t after_prefix = c->position + 1;
    if (c->size - after_prefix < n) { return 0; }
    *start = &c->bytes[after_prefix];
    *length = n;
    c->position = after_prefix + n;
    return 1;
}

static void attempt(Cursor *c, const char *label) {
    const unsigned char *start = NULL;
    size_t length = 0;
    if (take_slice(c, &start, &length)) {
        printf("%s: ok \"%.*s\", position %zu\n", label, (int)length, (const char *)start, c->position);
    } else {
        printf("%s: failed, position %zu\n", label, c->position);
    }
}

int main(void) {
    const unsigned char input[7] = {3, 'a', 'b', 'c', 2, 'x', 'y'};
    Cursor c = {input, 6, 0};
    attempt(&c, "first");
    attempt(&c, "second, 1 of 2 bytes");
    c.size = 7;
    attempt(&c, "second, after more input");
    attempt(&c, "at end");
    return 0;
}
Text
first: ok "abc", position 4
second, 1 of 2 bytes: failed, position 4
second, after more input: ok "xy", position 7
at end: failed, position 7

The first check proves there is a prefix octet. after_prefix is then at most size, so c->size - after_prefix cannot wrap, and comparing it with n never adds. Only after both checks do the three stores happen. Because the second attempt left the position at 4, the retry after the input grew re-read the prefix 2 and returned xy. The returned pointer is a borrowed view: it is valid only while the caller's input buffer is, which Day 5 returns to. Next, the cursor meets a length field whose value must be checked before any payload is read.

Was this article helpful?

Your response is saved on this device.