vhost: use struct_size and size_add to compute flex array sizes
authorJacob Keller <jacob.e.keller@intel.com>
Mon, 27 Feb 2023 21:41:27 +0000 (13:41 -0800)
committerMichael S. Tsirkin <mst@redhat.com>
Fri, 21 Apr 2023 07:02:29 +0000 (03:02 -0400)
The vhost_get_avail_size and vhost_get_used_size functions compute the size
of structures with flexible array members with an additional 2 bytes if the
VIRTIO_RING_F_EVENT_IDX feature flag is set. Convert these functions to use
struct_size() and size_add() instead of coding the calculation by hand.

This ensures that the calculations will saturate at SIZE_MAX rather than
overflowing.

Signed-off-by: Jacob Keller <jacob.e.keller@intel.com>
Cc: "Michael S. Tsirkin" <mst@redhat.com>
Cc: Jason Wang <jasowang@redhat.com>
Cc: virtualization@lists.linux-foundation.org
Cc: kvm@vger.kernel.org
Message-Id: <20230227214127.3678392-1-jacob.e.keller@intel.com>
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
drivers/vhost/vhost.c

index f11bdbe..43fa626 100644 (file)
@@ -436,8 +436,7 @@ static size_t vhost_get_avail_size(struct vhost_virtqueue *vq,
        size_t event __maybe_unused =
               vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
 
-       return sizeof(*vq->avail) +
-              sizeof(*vq->avail->ring) * num + event;
+       return size_add(struct_size(vq->avail, ring, num), event);
 }
 
 static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
@@ -446,8 +445,7 @@ static size_t vhost_get_used_size(struct vhost_virtqueue *vq,
        size_t event __maybe_unused =
               vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;
 
-       return sizeof(*vq->used) +
-              sizeof(*vq->used->ring) * num + event;
+       return size_add(struct_size(vq->used, ring, num), event);
 }
 
 static size_t vhost_get_desc_size(struct vhost_virtqueue *vq,