@samitouri / QOSamiQemu / commits / fa9c0c9f71

virtio-snd: check for overflow before g_malloc0

Coverity points out one g_malloc0 overflow, but it seems to be a false positive. Add a check to it regardless to fortify the code, and also add checks for every other g_malloc0 use. Resolves: Coverity CID 1547527 Signed-off-by: Manos Pitsidianakis <manos.pitsidianakis@linaro.org> Reviewed-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Message-ID: <20260420-virtio-fixups-v3-2-07aef1eff9d2@linaro.org>

Manos Pitsidianakis committed Apr 20, 2026 at 08:07 UTC fa9c0c9f716e39309ffdd95a5b7afc33cc0692d8
1 file changed +12 -4
hw/audio/virtio-snd.c
+12 -4
@@ -850,7 +850,7 @@ static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
850 VirtIOSound *vsnd = VIRTIO_SND(vdev);
851 VirtIOSoundPCMBuffer *buffer;
852 VirtQueueElement *elem;
853 - size_t msg_sz, size;
853 + size_t msg_sz, size, tmp;
854 virtio_snd_pcm_xfer hdr;
855 uint32_t stream_id;
856 /*
@@ -880,6 +880,8 @@ static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
880 if (msg_sz != sizeof(virtio_snd_pcm_xfer)) {
881 goto tx_err;
882 }
883 + assert(iov_size(elem->out_sg, elem->out_num) >= msg_sz);
884 + size = iov_size(elem->out_sg, elem->out_num) - msg_sz;
885 stream_id = le32_to_cpu(hdr.stream_id);
886
887 if (stream_id >= vsnd->snd_conf.streams
@@ -892,9 +894,11 @@ static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
894 goto tx_err;
895 }
896
897 + /* Check for g_malloc0 overflow. */
898 + if (!g_size_checked_add(&tmp, sizeof(VirtIOSoundPCMBuffer), size)) {
899 + goto tx_err;
900 + }
901 WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
896 - size = iov_size(elem->out_sg, elem->out_num) - msg_sz;
897 -
902 buffer = g_malloc0(sizeof(VirtIOSoundPCMBuffer) + size);
903 buffer->elem = elem;
904 buffer->populated = false;
@@ -932,7 +936,7 @@ static void virtio_snd_handle_rx_xfer(VirtIODevice *vdev, VirtQueue *vq)
936 VirtIOSound *vsnd = VIRTIO_SND(vdev);
937 VirtIOSoundPCMBuffer *buffer;
938 VirtQueueElement *elem;
935 - size_t msg_sz, size;
939 + size_t msg_sz, size, tmp;
940 virtio_snd_pcm_xfer hdr;
941 uint32_t stream_id;
942 /*
@@ -977,6 +981,10 @@ static void virtio_snd_handle_rx_xfer(VirtIODevice *vdev, VirtQueue *vq)
981 goto rx_err;
982 }
983 size -= sizeof(virtio_snd_pcm_status);
984 + /* Check for g_malloc0 overflow. */
985 + if (!g_size_checked_add(&tmp, sizeof(VirtIOSoundPCMBuffer), size)) {
986 + goto rx_err;
987 + }
988 WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
989 buffer = g_malloc0(sizeof(VirtIOSoundPCMBuffer) + size);
990 buffer->elem = elem;