Andrew Scull | b3d5fca | 2022-05-30 10:00:13 +0000 | [diff] [blame^] | 1 | /* SPDX-License-Identifier: GPL-2.0+ */ |
| 2 | /* |
| 3 | * Copyright (c) 2022 Google, Inc. |
| 4 | * Written by Andrew Scull <ascull@google.com> |
| 5 | */ |
| 6 | |
| 7 | #include <common.h> |
| 8 | #include <dm.h> |
| 9 | #include <virtio.h> |
| 10 | #include <virtio_ring.h> |
| 11 | #include <test/fuzz.h> |
| 12 | |
| 13 | static int fuzz_vring(const uint8_t *data, size_t size) |
| 14 | { |
| 15 | struct udevice *bus, *dev; |
| 16 | struct virtio_dev_priv *uc_priv; |
| 17 | struct virtqueue *vq; |
| 18 | struct virtio_sg sg[2]; |
| 19 | struct virtio_sg *sgs[2]; |
| 20 | unsigned int len; |
| 21 | u8 buffer[2][32]; |
| 22 | |
| 23 | /* hackily hardcode vring sizes */ |
| 24 | size_t num = 4; |
| 25 | size_t desc_size = (sizeof(struct vring_desc) * num); |
| 26 | size_t avail_size = (3 + num) * sizeof(u16); |
| 27 | size_t used_size = (3 * sizeof(u16)) + (sizeof(struct vring_used_elem) * num); |
| 28 | |
| 29 | if (size < (desc_size + avail_size + used_size)) |
| 30 | return 0; |
| 31 | |
| 32 | /* check probe success */ |
| 33 | if (uclass_first_device(UCLASS_VIRTIO, &bus) || !bus) |
| 34 | panic("Could not find virtio bus\n"); |
| 35 | |
| 36 | /* check the child virtio-rng device is bound */ |
| 37 | if (device_find_first_child(bus, &dev) || !dev) |
| 38 | panic("Could not find virtio device\n"); |
| 39 | |
| 40 | /* |
| 41 | * fake the virtio device probe by filling in uc_priv->vdev |
| 42 | * which is used by virtio_find_vqs/virtio_del_vqs. |
| 43 | */ |
| 44 | uc_priv = dev_get_uclass_priv(bus); |
| 45 | uc_priv->vdev = dev; |
| 46 | |
| 47 | /* prepare the scatter-gather buffer */ |
| 48 | sg[0].addr = buffer[0]; |
| 49 | sg[0].length = sizeof(buffer[0]); |
| 50 | sg[1].addr = buffer[1]; |
| 51 | sg[1].length = sizeof(buffer[1]); |
| 52 | sgs[0] = &sg[0]; |
| 53 | sgs[1] = &sg[1]; |
| 54 | |
| 55 | if (virtio_find_vqs(dev, 1, &vq)) |
| 56 | panic("Could not find vqs\n"); |
| 57 | if (virtqueue_add(vq, sgs, 0, 1)) |
| 58 | panic("Could not add to virtqueue\n"); |
| 59 | /* Simulate device writing to vring */ |
| 60 | memcpy(vq->vring.desc, data, desc_size); |
| 61 | memcpy(vq->vring.avail, data + desc_size, avail_size); |
| 62 | memcpy(vq->vring.used, data + desc_size + avail_size, used_size); |
| 63 | /* Make sure there is a response */ |
| 64 | if (vq->vring.used->idx == 0) |
| 65 | vq->vring.used->idx = 1; |
| 66 | virtqueue_get_buf(vq, &len); |
| 67 | if (virtio_del_vqs(dev)) |
| 68 | panic("Could not delete vqs\n"); |
| 69 | |
| 70 | return 0; |
| 71 | } |
| 72 | FUZZ_TEST(fuzz_vring, 0); |