Fix the bounds check in a frame walker

Review the AI's codeEasy10 min

Your task

A C parser walked the frames in a packet with a signed length byte. A fuzzer found an infinite loop on a length of 0xFF, read as -1, and out-of-bounds reads near the end of the buffer. The fix reads the length as unsigned and stops at the first frame that cannot be parsed safely.

An assistant wrote walk_frames(buf, total). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • buf: the packet's bytes, as a list of integers from 0 to 255.
  • total: how many bytes of buf are valid, as the caller reports it.
  • Return the length of every frame parsed, in order.

Rules the tests check:

  • The valid region is the first total bytes, but never more than the length of buf and never less than 0.
  • A frame is one length byte, then that many payload bytes. Frames follow each other from index 0.
  • Stop at the first frame whose length byte is 0, because it would never move the cursor forward.
  • Stop at the first frame whose length byte and payload do not both fit inside the valid region.
  • Stop at the end of the valid region. Return the lengths of the frames parsed before stopping.

Examples

walk_frames(buf: list[int], total: int) -> list[int]
Example 1
Inputwalk_frames([2, 65, 66, 3, 67, 68, 69], 7)
Output[2, 3]
Example 2
Inputwalk_frames([255, 65, 66], 3)
Output[]
Example 3
Inputwalk_frames([0, 65], 2)
Output[]