Parse a virtqueue descriptor chain.
#include <stdint.h>
#include <stddef.h>
#define VRING_DESC_F_NEXT 1
#define VRING_DESC_F_WRITE 2 /* device writes into this buffer */
struct vring_desc { uint64_t addr; uint32_t len; uint16_t flags; uint16_t next; };
typedef struct { uint8_t *ptr; uint32_t len; int device_writable; } iov_t;
uint8_t *gpa_to_hva_simple(uint64_t gpa, uint32_t len); /* NULL if invalid */
/* walk the chain starting at `head`; returns number of buffers, or -1 if malformed */
int parse_chain(const struct vring_desc *desc, uint16_t qsize, uint16_t head,
iov_t *iov, int max_iov)
{
int n = 0;
uint16_t i = head;
for (int hops = 0; ; hops++) {
if (i >= qsize || hops >= qsize || n >= max_iov) return -1; /* bad index, loop, too long */
const struct vring_desc *d = &desc[i]; /* copy fields once in real code */
uint8_t *p = gpa_to_hva_simple(d->addr, d->len);
if (!p) return -1; /* buffer outside guest RAM */
iov[n].ptr = p;
iov[n].len = d->len;
iov[n].device_writable = (d->flags & VRING_DESC_F_WRITE) != 0;
n++;
if (!(d->flags & VRING_DESC_F_NEXT)) break;
i = d->next;
}
return n;
}
Points: a request (e.g. a virtio-blk read) is a chain of descriptors linked by next: device-readable buffers (header, data to write) followed by device-writable ones (data to read, status byte). The device takes chain heads from the available ring, processes them, and puts (head, bytes written) into the used ring, then notifies the guest. Security checks are the core of the question: index range, loop detection (a chain can be at most qsize long), address translation with length checks, and reading each descriptor once (the guest can change shared memory while you read it: "double fetch" bugs). Indirect descriptors and the packed ring layout are follow-ups.