Skip to contentSkip to conversation

Various audio, chardev, ui and hw fixes

PATCH In review Marc-André Lureau 6 participants 77 messages Oct 4 – Oct 19

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover Various audio, chardev, ui and hw fixes

Hi

This series addresses a collection of bugs reported by Pavee Hui at
https://gitlab.com/qemu-project/qemu/-/work_items/4560, most likley with AI assitance. None of them should deserve a confidential level, imho.

I reviewed each reported issue against the code, and wrote individual fixes, using Claude as a review assistant. Several reported issues were dropped after review as incorrect or already addressed upstream. The remaining fixes were split into bisectable commits.

---
Marc-André Lureau (63):
audio/ossaudio: fix ioctl passing address-of-pointer instead of pointer audio/dbusaudio: fix off-by-one in volume channel assertion audio/ossaudio: fix off-by-one in mmap buffer size assertion audio/paaudio: fix server string in PAConnection audio/paaudio: avoid pidfile path truncation
audio/pwaudio: fix capture buffer leak on early return paths audio/pwaudio: clamp overrun writes to remaining ring buffer space audio/pwaudio: fix integer underflow in qpw_read() audio/pwaudio: handle negative avail in qpw_write and qpw_buffer_get_free audio/pwaudio: bail out on underrun in qpw_write audio/audio-mixeng-be: add upper bounds to audio settings validation audio/wavcapture: prevent freq overflow and corrupted WAV header ui/clipboard: clean up vm change state handler on last peer unregister ui/console: skip empty update regions in qemu_console_update ui/console: use QLIST_FOREACH_SAFE in dpy_refresh
ui/input: fix integer overflow in qemu_input_scale_axis ui/vnc-enc-zrle: propagate zrle_compress_data error ui/vnc-jobs: assert rect coordinates and dimensions in vnc_job_add_rect chardev/char-pty: free pty_name in finalize chardev/char-ringbuf: reject zero size with is_power_of_2 chardev/char-ringbuf: use actual read length in qmp_ringbuf_read chardev/char-udp: clarify read_poll return value with pending data chardev/char: fix use-after-free on mux creation failure hw/audio/gusemu_mixer: fix integer overflow in volume ramping hw/audio/gusemu_mixer: use unsigned literal for IRQ bit shifts hw/char/cadence_uart: fix RX FIFO overflow handling hw/char/cadence_uart: use correct interrupt for TX FIFO overflow hw/char/cadence_uart: validate FIFO indices in post_load hw/char/cadence_uart: fix post_load return value for invalid baud rate hw/char/escc: validate channel register index in post_load hw/char/exynos4210_uart: fix baud rate calculation operator precedence hw/char/exynos4210_uart: enforce 32-bit MMIO access size hw/char/ibex_uart: prevent division by zero on baud rate calculation hw/char/imx_serial: update interrupts after status register writes hw/char/serial: clamp zero baud rate to default hw/char/sh_serial: fix RDF flag clear on FIFO reset hw/char/sh_serial: use rx_cnt for available FIFO space hw/char/sh_serial: fix break detection flag hw/char/terminal3270: fix output buffer size for IAC-escaped header hw/char/terminal3270: consume processed input data hw/char/terminal3270: fix pre-handshake outbound data check hw/char/virtio-serial-bus: validate scatter-gather state in post_load hw/display/ramfb: validate guest-supplied stride hw/display/ramfb: fix map/unmap region size mismatch hw/display/ssd0323: mask SPI data to 8 bits hw/display/ssd0323: fix signed modulo in column/row commands hw/display/xenfb: fix 24-bit pixel read in BLT macro hw/input/adb: reject zero-length requests
hw/input/adb: validate devaddr on migration load hw/input/adb: report error when too many devices are registered hw/input/adb-kbd: validate WRITEREG request buffer length hw/input/adb-kbd: validate ring buffer indices on migration load hw/input/adb-kbd: check for errors after parent realize hw/input/adb-kbd: guard parent_unrealize against NULL hw/input/adb-mouse: validate WRITEREG request buffer length hw/input/adb-mouse: check for errors after parent realize hw/input/adb-mouse: add unrealize handler to unregister input hw/input/hid: validate queue length and key count on migration load hw/input/hid: fix off-by-one in pointer queue access on migration load hw/input/pl050: remove duplicate class_init assignment hw/input/stellaris_gamepad: deassert IRQs on reset hw/input/virtio-input: free VirtQueueElement in error unwind path hw/input/virtio-input: document queue preservation on device reset

 audio/audio-mixeng-be.c      |  4 ++--
 audio/dbusaudio.c            |  4 ++--
 audio/ossaudio.c             |  4 ++--
 audio/paaudio.c              |  6 ++++--
 audio/pwaudio.c              | 22 ++++++++++++++++++++--
 audio/wavcapture.c           |  6 ++++++
 chardev/char-pty.c           |  1 +
 chardev/char-ringbuf.c       | 10 ++++++----
 chardev/char-udp.c           |  4 ++++
 chardev/char.c               |  1 +
 hw/audio/gusemu_mixer.c      | 16 +++++++++-------
 hw/char/cadence_uart.c       | 26 ++++++++++++++++----------
 hw/char/escc.c               | 11 +++++++++++
 hw/char/exynos4210_uart.c    |  6 +++++-
 hw/char/ibex_uart.c          |  8 ++++++--
 hw/char/imx_serial.c         |  3 +++
 hw/char/serial.c             |  3 +++
 hw/char/sh_serial.c          |  6 +++---
 hw/char/terminal3270.c       | 15 ++++++---------
 hw/char/virtio-serial-bus.c  |  6 ++++++
 hw/display/ramfb.c           | 10 ++++++++--
 hw/display/ssd0323.c         |  9 +++++----
 hw/display/xenfb.c           | 19 +++++++++++++------
 hw/input/adb-kbd.c           | 29 ++++++++++++++++++++++++++++-
 hw/input/adb-mouse.c         | 23 +++++++++++++++++++++++
 hw/input/adb.c               | 17 +++++++++++++++++
 hw/input/hid.c               |  9 ++++++++-
 hw/input/pl050.c             |  1 -
 hw/input/stellaris_gamepad.c |  3 +++
 hw/input/virtio-input.c      |  5 +++++
 ui/clipboard.c               |  4 ++++
 ui/console.c                 |  7 +++++--
 ui/input.c                   |  8 +++++++-
 ui/vnc-enc-zrle.c            | 19 ++++++++++++++-----
 ui/vnc-jobs.c                |  1 +
 35 files changed, 257 insertions(+), 69 deletions(-)

---
base-commit: 2a0ac9c8ac2d303ca515dc819043409aef18cab5
change-id: 20261002-issue-4560-a704c9fc737f

Best regards,

Signature · 1 line
Marc-André Lureau <[email protected]>
#1 lore raw

PATCH 1/63 audio/ossaudio: fix ioctl passing address-of-pointer instead of pointer

oss_get_version() passes &version to ioctl(), but version is already an int*, so &version is int** which writes to the wrong address on the stack. Pass version directly.

Fixes 72ff25e4e98d ("Workaround for broken OSS_GETVERSION on FreeBSD, part two")
---
 audio/ossaudio.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
audio/ossaudio.c +1 -1
index 63c6e0a291f1..95a07ea1cace 100644
@@ -204,7 +204,7 @@ static int oss_to_audfmt (int ossfmt, AudioFormat *fmt, bool *big_endian)
 #ifdef USE_DSP_POLICY
 static int oss_get_version (int fd, int *version, const char *typ)
 {
-    if (ioctl (fd, OSS_GETVERSION, &version)) {
+    if (ioctl(fd, OSS_GETVERSION, version)) {
 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
         /*
          * Looks like atm (20100109) FreeBSD knows OSS_GETVERSION
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#2 lore raw

PATCH 2/63 audio/dbusaudio: fix off-by-one in volume channel assertion

In reply to Marc-André Lureau

The assertion vol->channels < sizeof(vol->vol) rejects the valid case where channels exactly equals the array size. Use <= instead.

Fixes 739362d4205c ("audio: add "dbus" audio backend")
---
 audio/dbusaudio.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
audio/dbusaudio.c +2 -2
index e9bdf6adb5bd..7d762fe873cf 100644
@@ -242,7 +242,7 @@ dbus_volume_out_listener(HWVoiceOut *hw,
         return;
     }
 
-    assert(vol->channels < sizeof(vol->vol));
+    assert(vol->channels <= sizeof(vol->vol));
     bytes = g_bytes_new(vol->vol, vol->channels);
     v_vol = g_variant_new_from_bytes(G_VARIANT_TYPE("ay"), bytes, TRUE);
     qemu_dbus_display1_audio_out_listener_call_set_volume(
@@ -332,7 +332,7 @@ dbus_volume_in_listener(HWVoiceIn *hw,
         return;
     }
 
-    assert(vol->channels < sizeof(vol->vol));
+    assert(vol->channels <= sizeof(vol->vol));
     bytes = g_bytes_new(vol->vol, vol->channels);
     v_vol = g_variant_new_from_bytes(G_VARIANT_TYPE("ay"), bytes, TRUE);
     qemu_dbus_display1_audio_in_listener_call_set_volume(
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#3 lore raw

PATCH 3/63 audio/ossaudio: fix off-by-one in mmap buffer size assertion

In reply to Marc-André Lureau

oss_put_buffer_out() asserts size < hw->size_emul, but a write that fills the entire buffer (size == size_emul) is valid. Use <= instead.

Fixes 3ba4066d085f ("ossaudio: port to the new audio backend api")
---
 audio/ossaudio.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
audio/ossaudio.c +1 -1
index 95a07ea1cace..e35eab3110e5 100644
@@ -393,7 +393,7 @@ static size_t oss_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
 {
     OSSVoiceOut *oss = (OSSVoiceOut *) hw;
     if (oss->mmapped) {
-        assert(buf == hw->buf_emul + hw->pos_emul && size < hw->size_emul);
+        assert(buf == hw->buf_emul + hw->pos_emul && size <= hw->size_emul);
 
         hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
         return size;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#4 lore raw

PATCH 4/63 audio/paaudio: fix server string in PAConnection

In reply to Marc-André Lureau

qpa_conn_init() receives a server string but never stores it. Save a copy with g_strdup() and free it in qpa_conn_fini(), as intended in original commit to allow connection reuse.

Fixes 9d34e6d8a1a1 ("paaudio: prepare for multiple audiodev")
---
 audio/paaudio.c | 2 ++
 1 file changed, 2 insertions(+)
audio/paaudio.c +2 -0
index 24327ecbf453..9d0a622fc5e6 100644
@@ -747,6 +747,7 @@ static void qpa_validate_per_direction_opts(Audiodev *dev,
 static void *qpa_conn_init(const char *server)
 {
     PAConnection *c = g_new0(PAConnection, 1);
+    c->server = g_strdup(server);
     QTAILQ_INSERT_TAIL(&pa_conns, c, list);
 
     c->mainloop = pa_threaded_mainloop_new();
@@ -875,6 +876,7 @@ static void qpa_conn_fini(PAConnection *c)
     }
 
     QTAILQ_REMOVE(&pa_conns, c, list);
+    g_free(c->server);
     g_free(c);
 }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#5 lore raw

PATCH 5/63 audio/paaudio: avoid pidfile path truncation

In reply to Marc-André Lureau

The pidfile path is built with snprintf() into a 64-byte stack buffer, which can silently truncate when XDG_RUNTIME_DIR is long. Use g_strdup_printf() with g_autofree instead.

Fixes d175505bd68d ("audio: check for pulseaudio daemon pidfile")
---
 audio/paaudio.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
audio/paaudio.c +2 -2
index 9d0a622fc5e6..358595c0460e 100644
@@ -819,7 +819,7 @@ audio_pa_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
     }
 
     if (!popts->server) {
-        char pidfile[64];
+        g_autofree char *pidfile = NULL;
         char *runtime;
         struct stat st;
 
@@ -828,7 +828,7 @@ audio_pa_realize(AudioBackend *abe, Audiodev *dev, Error **errp)
             error_setg(errp, "XDG_RUNTIME_DIR not set");
             return false;
         }
-        snprintf(pidfile, sizeof(pidfile), "%s/pulse/pid", runtime);
+        pidfile = g_strdup_printf("%s/pulse/pid", runtime);
         if (stat(pidfile, &st) != 0) {
             error_setg_errno(errp, errno, "could not stat pidfile %s", pidfile);
             return false;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#6 lore raw

PATCH 6/63 audio/pwaudio: fix capture buffer leak on early return paths

In reply to Marc-André Lureau

capture_on_process() leaks the PipeWire buffer on the p == NULL and underrun early-return paths by not calling pw_stream_queue_buffer(). The stream eventually starves from its buffer pool.

Fixes c2d3d1c29415 ("audio/pwaudio.c: Add Pipewire audio backend for QEMU")
---
 audio/pwaudio.c | 3 +++
 1 file changed, 3 insertions(+)
audio/pwaudio.c +3 -0
index a59c22e60b87..af360e2ec5ed 100644
@@ -171,6 +171,7 @@ capture_on_process(void *data)
     buf = b->buffer;
     p = buf->datas[0].data;
     if (p == NULL) {
+        pw_stream_queue_buffer(v->stream, b);
         return;
     }
     offs = SPA_MIN(buf->datas[0].chunk->offset, buf->datas[0].maxsize);
@@ -181,6 +182,8 @@ capture_on_process(void *data)
 
     if (filled < 0) {
         error_report("%p: underrun write:%u filled:%d", p, index, filled);
+        pw_stream_queue_buffer(v->stream, b);
+        return;
     } else {
         if ((uint32_t) filled + n_bytes > RINGBUFFER_SIZE) {
             error_report("%p: overrun write:%u filled:%d + size:%u > max:%u",
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#7 lore raw

PATCH 7/63 audio/pwaudio: clamp overrun writes to remaining ring buffer space

In reply to Marc-André Lureau

On overrun in both capture and playback paths, the code logs an error but proceeds to write the full unclamped size. This advances the write index past read_index + RINGBUFFER_SIZE, causing filled to exceed the buffer capacity on subsequent calls. Once in that state, avail goes negative and the signed/unsigned comparison fails to clamp further writes, leaving the ring buffer in a degenerate state.

Clamp to the remaining space so the write index stays within bounds.

Fixes c2d3d1c29415 ("audio/pwaudio.c: Add Pipewire audio backend for QEMU")
---
 audio/pwaudio.c | 2 ++
 1 file changed, 2 insertions(+)
audio/pwaudio.c +2 -0
index af360e2ec5ed..1105e920f3c2 100644
@@ -188,6 +188,7 @@ capture_on_process(void *data)
         if ((uint32_t) filled + n_bytes > RINGBUFFER_SIZE) {
             error_report("%p: overrun write:%u filled:%d + size:%u > max:%u",
             p, index, filled, n_bytes, RINGBUFFER_SIZE);
+            n_bytes = RINGBUFFER_SIZE - (uint32_t)filled;
         }
     }
     spa_ringbuffer_write_data(&v->ring,
@@ -318,6 +319,7 @@ qpw_write(HWVoiceOut *hw, void *data, size_t len)
         if ((uint32_t) filled + len > RINGBUFFER_SIZE) {
             error_report("%p: overrun write:%u filled:%d + size:%zu > max:%u",
             pw, index, filled, len, RINGBUFFER_SIZE);
+            len = RINGBUFFER_SIZE - (uint32_t)filled;
         }
     }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#8 lore raw

PATCH 8/63 audio/pwaudio: fix integer underflow in qpw_read()

In reply to Marc-André Lureau

qpw_read() casts len to int32_t for comparison with int32_t avail, which can underflow when avail is negative. Check for non-positive avail first, then cast to size_t for the comparison.

Fixes c2d3d1c29415 ("audio/pwaudio.c: Add Pipewire audio backend for QEMU")
---
 audio/pwaudio.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
audio/pwaudio.c +5 -1
index 1105e920f3c2..a8c18b9ecf85 100644
@@ -247,8 +247,12 @@ qpw_read(HWVoiceIn *hw, void *data, size_t len)
     avail = spa_ringbuffer_get_read_index(&v->ring, &index);
 
     trace_pw_read(avail, index, len);
+    if (avail <= 0) {
+        l = 0;
+        goto done_unlock;
+    }
 
-    if (avail < (int32_t) len) {
+    if ((size_t)avail < len) {
         len = avail;
     }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#9 lore raw

PATCH 9/63 audio/pwaudio: handle negative avail in qpw_write and qpw_buffer_get_free

In reply to Marc-André Lureau

qpw_write() and qpw_buffer_get_free() do not handle negative avail (highwater_mark - filled), which can occur transiently. In qpw_buffer_get_free(), clamp to zero. In qpw_write(), bail out early and fix the signed/unsigned comparison with len.

Fixes c2d3d1c29415 ("audio/pwaudio.c: Add Pipewire audio backend for QEMU")
---
 audio/pwaudio.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
audio/pwaudio.c +8 -1
index a8c18b9ecf85..8b3faae8a907 100644
@@ -286,6 +286,9 @@ static size_t qpw_buffer_get_free(HWVoiceOut *hw)
 
     filled = spa_ringbuffer_get_write_index(&v->ring, &index);
     avail = v->highwater_mark - filled;
+    if (avail < 0) {
+        avail = 0;
+    }
 
 done_unlock:
     pw_thread_loop_unlock(c->thread_loop);
@@ -312,8 +315,12 @@ qpw_write(HWVoiceOut *hw, void *data, size_t len)
     avail = v->highwater_mark - filled;
 
     trace_pw_write(filled, avail, index, len);
+    if (avail <= 0) {
+        len = 0;
+        goto done_unlock;
+    }
 
-    if (len > avail) {
+    if (len > (size_t)avail) {
         len = avail;
     }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#10 lore raw

PATCH 10/63 audio/pwaudio: bail out on underrun in qpw_write

In reply to Marc-André Lureau

When filled is negative (underrun), qpw_write() logs an error but falls through to spa_ringbuffer_write_data(). Bail out instead.

Fixes c2d3d1c29415 ("audio/pwaudio.c: Add Pipewire audio backend for QEMU")
---
 audio/pwaudio.c | 2 ++
 1 file changed, 2 insertions(+)
audio/pwaudio.c +2 -0
index 8b3faae8a907..18b371dc4f93 100644
@@ -326,6 +326,8 @@ qpw_write(HWVoiceOut *hw, void *data, size_t len)
 
     if (filled < 0) {
         error_report("%p: underrun write:%u filled:%d", pw, index, filled);
+        len = 0;
+        goto done_unlock;
     } else {
         if ((uint32_t) filled + len > RINGBUFFER_SIZE) {
             error_report("%p: overrun write:%u filled:%d + size:%zu > max:%u",
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#11 lore raw

PATCH 11/63 audio/audio-mixeng-be: add upper bounds to audio settings validation

In reply to Marc-André Lureau

Reject channel counts above 16 and sample rates above 384 kHz in audio_validate_settings(). Without upper bounds, extreme values can cause excessive memory allocation or arithmetic overflow downstream.

---
 audio/audio-mixeng-be.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
audio/audio-mixeng-be.c +2 -2
index f7d73d85608c..f6fd5014e0e0 100644
@@ -78,7 +78,7 @@ static int audio_validate_settings (const struct audsettings *as)
 {
     int invalid;
 
-    invalid = as->nchannels < 1;
+    invalid = as->nchannels < 1 || as->nchannels > 16;
 
     switch (as->fmt) {
     case AUDIO_FORMAT_S8:
@@ -94,7 +94,7 @@ static int audio_validate_settings (const struct audsettings *as)
         break;
     }
 
-    invalid |= as->freq <= 0;
+    invalid |= as->freq <= 0 || as->freq > 384000;
     return invalid ? -1 : 0;
 }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#12 lore raw

PATCH 12/63 audio/wavcapture: prevent freq overflow and corrupted WAV header

In reply to Marc-André Lureau

Reject freq <= 0 in wav_start_capture() early, before it is used to compute the WAV header fields.

---
 audio/wavcapture.c | 6 ++++++
 1 file changed, 6 insertions(+)
audio/wavcapture.c +6 -0
index 2dac94617104..67bac380ac7d 100644
@@ -131,6 +131,12 @@ int wav_start_capture(AudioBackend *state, CaptureState *s, const char *path,
         return -1;
     }
 
+    if (freq <= 0 || freq > 384000) {
+        error_report("invalid frequency %d, must be between 1 and 384000",
+                     freq);
+        return -1;
+    }
+
     stereo = nchannels == 2;
     bits16 = bits == 16;
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#13 lore raw

PATCH 13/63 ui/clipboard: clean up vm change state handler on last peer unregister

In reply to Marc-André Lureau

When the last clipboard peer unregisters, the vm change state handler is left dangling. Remove it to avoid stale callbacks after all peers are gone.

Fixes c967ff606b99 ("ui/clipboard: delay clipboard update when not running")
---
 ui/clipboard.c | 4 ++++
 1 file changed, 4 insertions(+)
ui/clipboard.c +4 -0
index e3d8a31ba9f7..46e602dfef43 100644
@@ -76,6 +76,10 @@ void qemu_clipboard_peer_unregister(QemuClipboardPeer *peer)
         qemu_clipboard_peer_release(peer, i);
     }
     notifier_remove(&peer->notifier);
+    if (QLIST_EMPTY(&clipboard_notifiers.notifiers)) {
+        g_clear_pointer(&cb_change_state_entry,
+                        qemu_del_vm_change_state_handler);
+    }
 }
 
 bool qemu_clipboard_peer_owns(QemuClipboardPeer *peer,
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#14 lore raw

PATCH 14/63 ui/console: skip empty update regions in qemu_console_update

In reply to Marc-André Lureau

After clamping coordinates to the surface dimensions, the resulting width or height can be zero. Proceeding with such values would pass degenerate rectangles to display listeners. Return early to avoid useless work.

Fixes 7c20b4a374d0 ("console: fix displaychangelisteners interface")
---
 ui/console.c | 3 +++
 1 file changed, 3 insertions(+)
ui/console.c +3 -0
index 14f148118e37..795c9857de82 100644
@@ -740,6 +740,9 @@ void qemu_console_update(QemuConsole *con, int x, int y, int w, int h)
     y = MIN(y, height);
     w = MIN(w, width - x);
     h = MIN(h, height - y);
+    if (w <= 0 || h <= 0) {
+        return;
+    }
 
     dpy_gfx_update_texture(con, con->surface, x, y, w, h);
     QLIST_FOREACH(dcl, &s->listeners, next) {
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#15 lore raw

PATCH 15/63 ui/console: use QLIST_FOREACH_SAFE in dpy_refresh

In reply to Marc-André Lureau

A display listener's dpy_refresh callback could potentially unregister itself from the listener list, which would invalidate the iteration pointer. Switch to QLIST_FOREACH_SAFE to allow safe removal during traversal.

---
 ui/console.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
ui/console.c +2 -2
index 795c9857de82..b7357172007e 100644
@@ -828,9 +828,9 @@ bool qemu_console_check_format(QemuConsole *con,
 
 static void dpy_refresh(DisplayState *s)
 {
-    DisplayChangeListener *dcl;
+    DisplayChangeListener *dcl, *next_dcl;
 
-    QLIST_FOREACH(dcl, &s->listeners, next) {
+    QLIST_FOREACH_SAFE(dcl, &s->listeners, next, next_dcl) {
         if (dcl->ops->dpy_refresh) {
             dcl->ops->dpy_refresh(dcl);
         }
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#16 lore raw

PATCH 16/63 ui/input: fix integer overflow in qemu_input_scale_axis

In reply to Marc-André Lureau

The multiplication of (value - min_in) * range_out can overflow int64_t when both operands are large. Use muldiv64() to compute the scaled result without overflow. Note that muldiv64() takes uint32_t for its multiplier and divisor, which is sufficient here since all function parameters are int (32-bit on all supported host architectures).

Fixes 43579403a3d6 ("input: mouse: add helpers functions to core")
---
 ui/input.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
ui/input.c +7 -1
index b82622c8645d..f40a9883701e 100644
@@ -5,6 +5,7 @@
 #include "trace.h"
 #include "ui/input.h"
 #include "ui/console.h"
+#include "qemu/host-utils.h"
 #include "system/replay.h"
 #include "system/runstate.h"
 
@@ -492,11 +493,16 @@ int qemu_input_scale_axis(int value,
 {
     int64_t range_in = (int64_t)max_in - min_in;
     int64_t range_out = (int64_t)max_out - min_out;
+    int64_t diff = (int64_t)value - min_in;
+    bool neg;
+    int64_t scaled;
 
     if (range_in < 1) {
         return min_out + range_out / 2;
     }
-    return ((int64_t)value - min_in) * range_out / range_in + min_out;
+    neg = (diff < 0) != (range_out < 0);
+    scaled = muldiv64(llabs(diff), llabs(range_out), llabs(range_in));
+    return (neg ? -scaled : scaled) + min_out;
 }
 
 void qemu_input_queue_rel(QemuConsole *src, InputAxis axis, int value)
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#17 lore raw

PATCH 17/63 ui/vnc-enc-zrle: propagate zrle_compress_data error

In reply to Marc-André Lureau

zrle_compress_data() returns -1 on failure, but the caller stored the result in a size_t, silently converting the error to a large positive value. Change to int to match the return type, add an Error **errp parameter replacing fprintf to stderr, and check for errors before using the result.

Fixes 148954faca58 ("vnc: Add ZRLE and ZYWRLE encodings.")
---
 ui/vnc-enc-zrle.c | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)
ui/vnc-enc-zrle.c +14 -5
index 7679014c9e33..c0702891b4f8 100644
@@ -27,6 +27,8 @@
  */
 
 #include "qemu/osdep.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
 #include "vnc.h"
 #include "vnc-enc-zrle.h"
 
@@ -69,7 +71,8 @@ static void *zrle_convert_fb(VncState *vs, VncZrle *zrle,
     return zrle->fb.buffer;
 }
 
-static int zrle_compress_data(VncState *vs, VncZrle *zrle, int level)
+static int zrle_compress_data(VncState *vs, VncZrle *zrle, int level,
+                              Error **errp)
 {
     z_streamp zstream = &zrle->stream;
 
@@ -85,7 +88,7 @@ static int zrle_compress_data(VncState *vs, VncZrle *zrle, int level)
                            MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
 
         if (err != Z_OK) {
-            fprintf(stderr, "VNC: error initializing zlib\n");
+            error_setg(errp, "ZRLE: error initializing zlib");
             return -1;
         }
 
@@ -104,7 +107,7 @@ static int zrle_compress_data(VncState *vs, VncZrle *zrle, int level)
 
     /* start encoding */
     if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {
-        fprintf(stderr, "VNC: error during zrle compression\n");
+        error_setg(errp, "ZRLE: error during compression");
         return -1;
     }
 
@@ -256,7 +259,8 @@ static int zrle_send_framebuffer_update(VncState *vs, VncWorker *worker,
                                         int x, int y, int w, int h)
 {
     bool be = vs->client_endian == G_BIG_ENDIAN;
-    size_t bytes;
+    Error *error = NULL;
+    int bytes;
     int zywrle_level;
 
     if (worker->zrle.type == VNC_ENCODING_ZYWRLE) {
@@ -336,7 +340,12 @@ static int zrle_send_framebuffer_update(VncState *vs, VncWorker *worker,
     }
 
     vnc_zrle_stop(vs, &worker->zrle);
-    bytes = zrle_compress_data(vs, &worker->zrle, Z_DEFAULT_COMPRESSION);
+    bytes = zrle_compress_data(vs, &worker->zrle, Z_DEFAULT_COMPRESSION,
+                               &error);
+    if (bytes < 0) {
+        error_report_err(error);
+        return -1;
+    }
     vnc_framebuffer_update(vs, x, y, w, h, worker->zrle.type);
     vnc_write_u32(vs, bytes);
     vnc_write(vs, worker->zrle.zlib.buffer, worker->zrle.zlib.offset);
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#18 lore raw

PATCH 18/63 ui/vnc-jobs: assert rect coordinates and dimensions in vnc_job_add_rect

In reply to Marc-André Lureau

All callers guarantee non-negative coordinates and positive dimensions. Add an assert to document the invariant that vnc_worker_clamp_rect relies on.

---
 ui/vnc-jobs.c | 1 +
 1 file changed, 1 insertion(+)
ui/vnc-jobs.c +1 -0
index 90b68bf4cb98..81c4fa5dbdbb 100644
@@ -87,6 +87,7 @@ int vnc_job_add_rect(VncJob *job, int x, int y, int w, int h)
 
     trace_vnc_job_add_rect(job->vs, job, x, y, w, h);
     assert(!QTAILQ_IN_USE(job, next));
+    assert(x >= 0 && y >= 0 && w > 0 && h > 0);
 
     entry->rect.x = x;
     entry->rect.y = y;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#19 lore raw

PATCH 19/63 chardev/char-pty: free pty_name in finalize

In reply to Marc-André Lureau

The pty_name field was added to PtyChardev state but never freed on object finalize, leaking the allocated string.

Fixes 1116f5176e7a ("chardev/char-pty: store pty_name into PtyChardev state")
---
 chardev/char-pty.c | 1 +
 1 file changed, 1 insertion(+)
chardev/char-pty.c +1 -0
index 7e95132cdbba..612607609c80 100644
@@ -215,6 +215,7 @@ static void char_pty_finalize(Object *obj)
         unlink(s->path);
         g_free(s->path);
     }
+    g_clear_pointer(&s->pty_name, g_free);
 
     pty_chr_state(chr, 0);
     object_unref(OBJECT(s->ioc));
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#20 lore raw

PATCH 20/63 chardev/char-ringbuf: reject zero size with is_power_of_2

In reply to Marc-André Lureau

The power-of-two validation did not reject size=0, since (0 & (0-1)) == 0. With a zero size, the ring buffer mask wraps to SIZE_MAX, causing out-of-bounds memory access. Use is_power_of_2() which handles zero correctly.

Fixes bf51f62869f4 ("char: move ringbuf/memory to its own file")
---
 chardev/char-ringbuf.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
chardev/char-ringbuf.c +2 -1
index 8f998d26a49f..a80519f8d65d 100644
@@ -27,6 +27,7 @@
 #include "qapi/error.h"
 #include "qapi/qapi-commands-char.h"
 #include "qemu/base64.h"
+#include "qemu/host-utils.h"
 #include "qemu/module.h"
 #include "qemu/option.h"
 #include "qom/object.h"
@@ -102,7 +103,7 @@ static bool ringbuf_chr_open(Chardev *chr,
     d->size = opts->has_size ? opts->size : 65536;
 
     /* The size must be power of 2 */
-    if (d->size & (d->size - 1)) {
+    if (!is_power_of_2(d->size)) {
         error_setg(errp, "size of ringbuf chardev must be power of two");
         return false;
     }
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#21 lore raw

PATCH 21/63 chardev/char-ringbuf: use actual read length in qmp_ringbuf_read

In reply to Marc-André Lureau

qmp_ringbuf_read() used the requested size rather than the actual number of bytes returned by ringbuf_chr_read() for base64 encoding and null-termination. Since ringbuf_count() is called without the lock, a concurrent writer can advance the consumer index, leaving fewer bytes available by the time ringbuf_chr_read() runs. This could encode uninitialized data or misplace the null terminator.

---
 chardev/char-ringbuf.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
chardev/char-ringbuf.c +4 -3
index a80519f8d65d..4d83663e9abc 100644
@@ -167,6 +167,7 @@ char *qmp_ringbuf_read(const char *device, int64_t size,
     Chardev *chr;
     uint8_t *read_data;
     size_t count;
+    int actual;
     char *data;
 
     chr = qemu_chr_find(device);
@@ -189,10 +190,10 @@ char *qmp_ringbuf_read(const char *device, int64_t size,
     size = size > count ? count : size;
     read_data = g_malloc(size + 1);
 
-    ringbuf_chr_read(chr, read_data, size);
+    actual = ringbuf_chr_read(chr, read_data, size);
 
     if (has_format && (format == DATA_FORMAT_BASE64)) {
-        data = g_base64_encode(read_data, size);
+        data = g_base64_encode(read_data, actual);
         g_free(read_data);
     } else {
         /*
@@ -202,7 +203,7 @@ char *qmp_ringbuf_read(const char *device, int64_t size,
          * when) ring buffer lost characters since last read, initial
          * continuation characters should be dropped.
          */
-        read_data[size] = 0;
+        read_data[actual] = 0;
         data = (char *)read_data;
     }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#22 lore raw

PATCH 22/63 chardev/char-udp: clarify read_poll return value with pending data

In reply to Marc-André Lureau

Add a comment explaining why returning s->max_size is safe when there is unflushed data in the buffer: udp_chr_flush_buffer() loops while max_size > 0, so max_size is guaranteed to be 0 when pending data remains.

---
 chardev/char-udp.c | 4 ++++
 1 file changed, 4 insertions(+)
chardev/char-udp.c +4 -0
index 423000832ffb..618fd8f135a0 100644
@@ -81,6 +81,10 @@ static int udp_chr_read_poll(void *opaque)
      */
     udp_chr_flush_buffer(s);
 
+    /*
+     * udp_chr_flush_buffer() loops while max_size > 0 && bufptr < bufcnt,
+     * so when pending data remains it must be because max_size hit 0.
+     */
     return s->max_size;
 }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#23 lore raw

PATCH 23/63 chardev/char: fix use-after-free on mux creation failure

In reply to Marc-André Lureau

When mux creation fails, object_unparent() drops the last reference on the base chardev, but 'base' was left dangling. The 'out' label then passes it to qemu_chardev_set_replay(), causing a use-after-free.

Set base to NULL after unparent so the replay path is skipped.

Fixes 4c193bb129da ("chardev: set record/replay on the base device of a muxed device")
---
 chardev/char.c | 1 +
 1 file changed, 1 insertion(+)
chardev/char.c +1 -0
index 9da0911e503c..7daf87f0363e 100644
@@ -747,6 +747,7 @@ static Chardev *do_qemu_chr_new_from_opts(QemuOpts *opts, GMainContext *context,
         mux = qemu_chardev_new(id, TYPE_CHARDEV_MUX, backend, context, errp);
         if (mux == NULL) {
             object_unparent(OBJECT(chr));
+            base = NULL;
             chr = NULL;
             goto out;
         }
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#24 lore raw

PATCH 24/63 hw/audio/gusemu_mixer: fix integer overflow in volume ramping

In reply to Marc-André Lureau

Volume32, StartVol32, and EndVol32 were unsigned int, but VolumeIncrement32 can be negative (reverse ramping), so Volume32 += VolumeIncrement32 wraps around instead of going negative. This breaks the boundary comparison and produces incorrect volume.

Change them to signed int and add a CLAMP to keep Volume32 within the valid range [0, 0x1fe000].

---
 hw/audio/gusemu_mixer.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
hw/audio/gusemu_mixer.c +5 -3
index 56300de77e44..341995cfd19e 100644
@@ -68,9 +68,10 @@ void gus_mixvoices(GUSEmuState * state, unsigned int playback_freq, unsigned int
 
             int             PanningPos = (GUSvoice(wVSRPanning) >> 8) & 0xf;
 
-            unsigned int    Volume32   = 32 * GUSvoice(wVSRCurrVol); /* 32 times larger than original gus for maintaining precision while ramping */
-            unsigned int    StartVol32 = (GUSvoice(wVSRVolRampStartVol) & 0xff00) * 32;
-            unsigned int    EndVol32   = (GUSvoice(wVSRVolRampEndVol)   & 0xff00) * 32;
+            /* 32x original GUS precision for ramping */
+            int Volume32 = 32 * GUSvoice(wVSRCurrVol);
+            int StartVol32 = (GUSvoice(wVSRVolRampStartVol) & 0xff00) * 32;
+            int EndVol32 = (GUSvoice(wVSRVolRampEndVol) & 0xff00) * 32;
             int             VolumeIncrement32 = (32 * 16 * (GUSvoice(wVSRVolRampRate) & 0x3f00) >> 8) >> ((((GUSvoice(wVSRVolRampRate) & 0xc000) >> 8) >> 6) * 3); /* including 1/8/64/512 volume speed divisor */
             VolumeIncrement32 = (((VolumeIncrement32 * 44100 / 2) / playback_freq) * 14) / ((GUSregb(NumVoices) & 31) + 1); /* adjust ramping speed to playback speed */
 
@@ -82,6 +83,7 @@ void gus_mixvoices(GUSEmuState * state, unsigned int playback_freq, unsigned int
             for (sample = 0; sample < numsamples; sample++)
             {
                 int             sample1, sample2, Volume;
+                Volume32 = CLAMP(Volume32, 0, 0x1fe000);
                 if (GUSvoice(wVSRControl) & 0x400)      /* 16bit */
                 {
                     int offset = ((CurrPos >> 9) & 0xc0000) + (((CurrPos >> 9) & 0x1ffff) << 1);
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#25 lore raw

PATCH 25/63 hw/audio/gusemu_mixer: use unsigned literal for IRQ bit shifts

In reply to Marc-André Lureau

Voice ranges up to 31 (NumVoices & 31), so 1 << 31 is undefined behavior in C as it shifts into the sign bit of a signed int. Use 1U to make the shift well-defined.

---
 hw/audio/gusemu_mixer.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
hw/audio/gusemu_mixer.c +4 -4
index 341995cfd19e..8dc4a68386b4 100644
@@ -133,11 +133,11 @@ void gus_mixvoices(GUSEmuState * state, unsigned int playback_freq, unsigned int
                 }
                 if ((GUSvoice(wVSRVolRampControl) & 0xa000) == 0xa000)  /* volramp IRQ set and enabled? */
                 {
-                    GUSregd(voicevolrampirq) |= 1 << Voice;             /* set irq slot */
+                    GUSregd(voicevolrampirq) |= 1U << Voice;            /* set irq slot */
                 }
                 else
                 {
-                    GUSregd(voicevolrampirq) &= (~(1 << Voice));        /* clear irq slot */
+                    GUSregd(voicevolrampirq) &= ~(1U << Voice); /* clear irq slot */
                     GUSvoice(wVSRVolRampControl) &= 0x7f00;
                 }
 
@@ -164,11 +164,11 @@ void gus_mixvoices(GUSEmuState * state, unsigned int playback_freq, unsigned int
                 }
                 if ((GUSvoice(wVSRControl) & 0xa000) == 0xa000)    /* wavetable IRQ set and enabled? */
                 {
-                    GUSregd(voicewavetableirq) |= 1 << Voice;      /* set irq slot */
+                    GUSregd(voicewavetableirq) |= 1U << Voice;      /* set irq slot */
                 }
                 else
                 {
-                    GUSregd(voicewavetableirq) &= (~(1 << Voice)); /* clear irq slot */
+                    GUSregd(voicewavetableirq) &= ~(1U << Voice); /* clear irq slot */
                     GUSvoice(wVSRControl) &= 0x7f00;
                 }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#26 lore raw

Re: [PATCH 25/63] hw/audio/gusemu_mixer: use unsigned literal for IRQ bit shifts

Quoted 4 lines · Marc-André Lureau

Voice ranges up to 31 (NumVoices & 31), so 1 << 31 is undefined behavior in C as it shifts into the sign bit of a signed int. Use 1U to make the shift well-defined.

This is *not* undefined behaviour for QEMU, because we use -fwrapv specifically to avoid it being UB. The change is reasonable enough, but we wouldn't be doing it for UB reasons.

-- PMM

#27 lore raw

Re: [PATCH 25/63] hw/audio/gusemu_mixer: use unsigned literal for IRQ bit shifts

Hi

Quoted 4 lines · Peter Maydell
Quoted 1 line · Marc-André Lureau
Quoted 8 lines
Quoted 3 lines

Voice ranges up to 31 (NumVoices & 31), so 1 << 31 is undefined behavior in C as it shifts into the sign bit of a signed int. Use 1U to make the shift well-defined.

This is *not* undefined behaviour for QEMU, because we use -fwrapv specifically to avoid it being UB. The change is reasonable enough, but we wouldn't be doing it for UB reasons.

Right, I'll adjust the commit message. And also update gusemu_hal.c for similar correctness fix
thanks

#28 lore raw

PATCH 26/63 hw/char/cadence_uart: fix RX FIFO overflow handling

In reply to Marc-André Lureau

The old code checked for overflow only once before the loop, which meant a multi-byte write could silently overflow the FIFO when there was space for some but not all bytes. Check per-byte instead, storing as many bytes as possible before flagging ROVR. Only arm the FIFO trigger timer when bytes were actually stored.

Fixes 35548b06cf55 ("cadence_uart: initial version of device model")
---
 hw/char/cadence_uart.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)
hw/char/cadence_uart.c +9 -7
index eff6a3c4d17a..ae11caa11b82 100644
@@ -284,14 +284,16 @@ static void uart_write_rx_fifo(void *opaque, const uint8_t *buf, int size)
         return;
     }
 
-    if (s->rx_count == CADENCE_UART_RX_FIFO_SIZE) {
-        s->r[R_CISR] |= UART_INTR_ROVR;
-    } else {
-        for (i = 0; i < size; i++) {
-            s->rx_fifo[s->rx_wpos] = buf[i];
-            s->rx_wpos = (s->rx_wpos + 1) % CADENCE_UART_RX_FIFO_SIZE;
-            s->rx_count++;
+    for (i = 0; i < size; i++) {
+        if (s->rx_count >= CADENCE_UART_RX_FIFO_SIZE) {
+            s->r[R_CISR] |= UART_INTR_ROVR;
+            break;
         }
+        s->rx_fifo[s->rx_wpos] = buf[i];
+        s->rx_wpos = (s->rx_wpos + 1) % CADENCE_UART_RX_FIFO_SIZE;
+        s->rx_count++;
+    }
+    if (i > 0) {
         timer_mod(s->fifo_trigger_handle, new_rx_time +
                                                 (s->char_tx_time * 4));
     }
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by Alistair Francis on v1 26/63
#29 lore raw

Re: [PATCH 26/63] hw/char/cadence_uart: fix RX FIFO overflow handling

Quoted 9 lines · Marc-André Lureau

The old code checked for overflow only once before the loop, which meant a multi-byte write could silently overflow the FIFO when there was space for some but not all bytes. Check per-byte instead, storing as many bytes as possible before flagging ROVR. Only arm the FIFO trigger timer when bytes were actually stored.

Fixes 35548b06cf55 ("cadence_uart: initial version of device model")

Alistair

Quoted 35 lines

---
 hw/char/cadence_uart.c | 16 +++++++++-------

 1 file changed, 9 insertions(+), 7 deletions(-)
hw/char/cadence_uart.c +0 -0
index eff6a3c4d17a..ae11caa11b82 100644
@@ -284,14 +284,16 @@ static void uart_write_rx_fifo(void *opaque,
 const uint8_t *buf, int size)
          return;
      }


-    if (s->rx_count == CADENCE_UART_RX_FIFO_SIZE) {
-        s->r[R_CISR] |= UART_INTR_ROVR;
-    } else {
-        for (i = 0; i < size; i++) {
-            s->rx_fifo[s->rx_wpos] = buf[i];
-            s->rx_wpos = (s->rx_wpos + 1) % CADENCE_UART_RX_FIFO_SIZE;
-            s->rx_count++;
+    for (i = 0; i < size; i++) {
+        if (s->rx_count >= CADENCE_UART_RX_FIFO_SIZE) { +            s->r[R_CISR] |= UART_INTR_ROVR;
+            break;
         }
+        s->rx_fifo[s->rx_wpos] = buf[i];
+        s->rx_wpos = (s->rx_wpos + 1) % CADENCE_UART_RX_FIFO_SIZE; +        s->rx_count++;
+    }
+    if (i > 0) {
         timer_mod(s->fifo_trigger_handle, new_rx_time + (s->char_tx_time * 4));
     }

#30 lore raw

PATCH 27/63 hw/char/cadence_uart: use correct interrupt for TX FIFO overflow

In reply to Marc-André Lureau

The TX FIFO overflow path was raising UART_INTR_ROVR (RX overflow) instead of UART_INTR_TOVR (TX overflow).

Fixes 86baecc3e435 ("char/cadence_uart: Use the TX fifo for transmission")
---
 hw/char/cadence_uart.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/cadence_uart.c +1 -1
index ae11caa11b82..c790372e98fb 100644
@@ -351,7 +351,7 @@ static void uart_write_tx_fifo(CadenceUARTState *s, const uint8_t *buf,
          * us to here.
          */
         qemu_log_mask(LOG_GUEST_ERROR, "cadence_uart: TxFIFO overflow");
-        s->r[R_CISR] |= UART_INTR_ROVR;
+        s->r[R_CISR] |= UART_INTR_TOVR;
     }
 
     memcpy(s->tx_fifo + s->tx_count, buf, size);
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by Alistair Francis on v1 27/63
#31 lore raw

Re: [PATCH 27/63] hw/char/cadence_uart: use correct interrupt for TX FIFO overflow

Quoted 7 lines · Marc-André Lureau

The TX FIFO overflow path was raising UART_INTR_ROVR (RX overflow) instead of UART_INTR_TOVR (TX overflow).

Fixes 86baecc3e435 ("char/cadence_uart: Use the TX fifo for

transmission")

Alistair

Quoted 19 lines

---
 hw/char/cadence_uart.c | 2 +-

 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/cadence_uart.c +0 -0
index ae11caa11b82..c790372e98fb 100644
@@ -351,7 +351,7 @@ static void uart_write_tx_fifo(CadenceUARTState
 *s, const uint8_t *buf,
           * us to here.
           */

         qemu_log_mask(LOG_GUEST_ERROR, "cadence_uart: TxFIFO overflow");
-        s->r[R_CISR] |= UART_INTR_ROVR;
+        s->r[R_CISR] |= UART_INTR_TOVR;
     }

     memcpy(s->tx_fifo + s->tx_count, buf, size);

#32 lore raw

PATCH 28/63 hw/char/cadence_uart: validate FIFO indices in post_load

In reply to Marc-André Lureau

Check that tx_count, rx_count, and rx_wpos are within valid bounds after migration to prevent out-of-bounds memory access from a corrupted or malicious migration stream.

Fixes 35548b06cf55 ("cadence_uart: initial version of device model")
---
 hw/char/cadence_uart.c | 5 +++++
 1 file changed, 5 insertions(+)
hw/char/cadence_uart.c +5 -0
index c790372e98fb..1a065e2429eb 100644
@@ -586,6 +586,11 @@ static int cadence_uart_post_load(void *opaque, int version_id)
 {
     CadenceUARTState *s = opaque;
 
+    if (s->tx_count > CADENCE_UART_TX_FIFO_SIZE ||
+        s->rx_count > CADENCE_UART_RX_FIFO_SIZE ||
+        s->rx_wpos >= CADENCE_UART_RX_FIFO_SIZE) {
+        return -EINVAL;
+    }
     /* Ensure these two aren't invalid numbers */
     if (s->r[R_BRGR] < 1 || s->r[R_BRGR] & ~0xFFFF ||
         s->r[R_BDIV] <= 3 || s->r[R_BDIV] & ~0xFF) {
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by Alistair Francis on v1 28/63
#33 lore raw

Re: [PATCH 28/63] hw/char/cadence_uart: validate FIFO indices in post_load

Quoted 7 lines · Marc-André Lureau

Check that tx_count, rx_count, and rx_wpos are within valid bounds after migration to prevent out-of-bounds memory access from a corrupted or malicious migration stream.

Fixes 35548b06cf55 ("cadence_uart: initial version of device model")

Alistair

Quoted 21 lines

---
 hw/char/cadence_uart.c | 5 +++++

 1 file changed, 5 insertions(+)
hw/char/cadence_uart.c +0 -0
index c790372e98fb..1a065e2429eb 100644
@@ -586,6 +586,11 @@ static int cadence_uart_post_load(void *opaque,
 int version_id)
  {
      CadenceUARTState *s = opaque;


+    if (s->tx_count > CADENCE_UART_TX_FIFO_SIZE || +        s->rx_count > CADENCE_UART_RX_FIFO_SIZE || +        s->rx_wpos >= CADENCE_UART_RX_FIFO_SIZE) { +        return -EINVAL;
+    }
     /* Ensure these two aren't invalid numbers */ if (s->r[R_BRGR] < 1 || s->r[R_BRGR] & ~0xFFFF || s->r[R_BDIV] <= 3 || s->r[R_BDIV] & ~0xFF) {

#34 lore raw

PATCH 29/63 hw/char/cadence_uart: fix post_load return value for invalid baud rate

In reply to Marc-André Lureau

post_load must return a negative errno on failure, but the BRGR/BDIV validation was returning 1 (positive), which the caller treats as success. Return -EINVAL instead.

Fixes 6e29651c5e3a ("char: cadence: check baud rate generator and divider values")
---
 hw/char/cadence_uart.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
hw/char/cadence_uart.c +1 -2
index 1a065e2429eb..263c28bb7197 100644
@@ -594,8 +594,7 @@ static int cadence_uart_post_load(void *opaque, int version_id)
     /* Ensure these two aren't invalid numbers */
     if (s->r[R_BRGR] < 1 || s->r[R_BRGR] & ~0xFFFF ||
         s->r[R_BDIV] <= 3 || s->r[R_BDIV] & ~0xFF) {
-        /* Value is invalid, abort */
-        return 1;
+        return -EINVAL;
     }
 
     uart_parameters_setup(s);
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by Alistair Francis on v1 29/63
#35 lore raw

Re: [PATCH 29/63] hw/char/cadence_uart: fix post_load return value for invalid baud rate

Quoted 8 lines · Marc-André Lureau

post_load must return a negative errno on failure, but the BRGR/BDIV validation was returning 1 (positive), which the caller treats as success. Return -EINVAL instead.

Fixes 6e29651c5e3a ("char: cadence: check baud rate generator and

divider values")

Alistair

Quoted 19 lines

---
 hw/char/cadence_uart.c | 3 +--

 1 file changed, 1 insertion(+), 2 deletions(-)
hw/char/cadence_uart.c +0 -0
index 1a065e2429eb..263c28bb7197 100644
@@ -594,8 +594,7 @@ static int cadence_uart_post_load(void *opaque,
 int version_id)
      /* Ensure these two aren't invalid numbers */

     if (s->r[R_BRGR] < 1 || s->r[R_BRGR] & ~0xFFFF || s->r[R_BDIV] <= 3 || s->r[R_BDIV] & ~0xFF) { -        /* Value is invalid, abort */
-        return 1;
+        return -EINVAL;
     }

     uart_parameters_setup(s);

#36 lore raw

PATCH 30/63 hw/char/escc: validate channel register index in post_load

In reply to Marc-André Lureau

Reject migrated state where the register index exceeds the valid range, preventing out-of-bounds access.

Fixes bdb78cae61ec ("escc: convert to VMState, vmsd and reset")
---
 hw/char/escc.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
hw/char/escc.c +11 -0
index 7aae627fb48f..1543ca680358 100644
@@ -764,10 +764,21 @@ static void serial_event(void *opaque, QEMUChrEvent event)
     }
 }
 
+static int escc_chn_post_load(void *opaque, int version_id)
+{
+    ESCCChannelState *s = opaque;
+
+    if (s->reg >= ESCC_SERIAL_REGS) {
+        return -EINVAL;
+    }
+    return 0;
+}
+
 static const VMStateDescription vmstate_escc_chn = {
     .name = "escc_chn",
     .version_id = 2,
     .minimum_version_id = 1,
+    .post_load = escc_chn_post_load,
     .fields = (const VMStateField[]) {
         VMSTATE_UINT32(vmstate_dummy, ESCCChannelState),
         VMSTATE_UINT32(reg, ESCCChannelState),
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#37 lore raw

PATCH 31/63 hw/char/exynos4210_uart: fix baud rate calculation operator precedence

In reply to Marc-André Lureau

The 0xffff mask was applied to the result of (16 * UBRDIV) instead of the register value itself, due to C operator precedence (* binds tighter than &). When UBRDIV >= 0x1000, the multiplication by 16 pushes bits past the 16-bit mask, producing a wrong baud rate calculation.

---
 hw/char/exynos4210_uart.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/exynos4210_uart.c +1 -1
index 9d1825150d1c..7240ff7b5c24 100644
@@ -327,7 +327,7 @@ static void exynos4210_uart_update_parameters(Exynos4210UartState *s)
 
     uclk_rate = 24000000;
 
-    speed = uclk_rate / ((16 * (s->reg[I_(UBRDIV)]) & 0xffff) +
+    speed = uclk_rate / ((16 * (s->reg[I_(UBRDIV)] & 0xffff)) +
             (s->reg[I_(UFRACVAL)] & 0x7) + 16);
 
     ssp.speed     = speed;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by on v1 31/63
#38 lore raw

Re: [PATCH 31/63] hw/char/exynos4210_uart: fix baud rate calculation operator precedence

hw/char/exynos4210_uart.c static void

Quoted 17 lines · Marc-André Lureau

The 0xffff mask was applied to the result of (16 * UBRDIV) instead of the register value itself, due to C operator precedence (* binds tighter than &). When UBRDIV >= 0x1000, the multiplication by 16 pushes bits past the 16-bit mask, producing a wrong baud rate calculation.

---
 hw/char/exynos4210_uart.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/exynos4210_uart.c +0 -0
index 9d1825150d1c..7240ff7b5c24 100644
@@ -327,7 +327,7 @@ static void

exynos4210_uart_update_parameters(Exynos4210UartState *s)

hw/char/exynos4210_uart.c static void exynos4210_uart_update_parameters(Exynos4210UartState *s) · line 333

Quoted 8 lines
hw/char/exynos4210_uart.c +1 -1
     uclk_rate = 24000000;
 
-    speed = uclk_rate / ((16 * (s->reg[I_(UBRDIV)]) & 0xffff) +
+    speed = uclk_rate / ((16 * (s->reg[I_(UBRDIV)] & 0xffff)) +
             (s->reg[I_(UFRACVAL)] & 0x7) + 16);
 
     ssp.speed     = speed;

thanks
-- PMM

#39 lore raw

PATCH 32/63 hw/char/exynos4210_uart: enforce 32-bit MMIO access size

In reply to Marc-André Lureau

Set .impl min/max_access_size to 4 bytes so the memory subsystem synthesizes sub-word guest accesses into 32-bit handler calls. The read/write handlers ignore the size parameter and always operate on full 32-bit register values, so without this QEMU would not extract the correct byte or halfword from the result.

---
 hw/char/exynos4210_uart.c | 4 ++++
 1 file changed, 4 insertions(+)
hw/char/exynos4210_uart.c +4 -0
index 7240ff7b5c24..8774d4bb43d7 100644
@@ -506,6 +506,10 @@ static const MemoryRegionOps exynos4210_uart_ops = {
         .max_access_size = 4,
         .unaligned = false
     },
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
 };
 
 static int exynos4210_uart_can_receive(void *opaque)
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#40 lore raw

Re: [PATCH 32/63] hw/char/exynos4210_uart: enforce 32-bit MMIO access size

Quoted 18 lines · Marc-André Lureau

Set .impl min/max_access_size to 4 bytes so the memory subsystem synthesizes sub-word guest accesses into 32-bit handler calls. The read/write handlers ignore the size parameter and always operate on full 32-bit register values, so without this QEMU would not extract the correct byte or halfword from the result.

---
 hw/char/exynos4210_uart.c | 4 ++++
 1 file changed, 4 insertions(+)
hw/char/exynos4210_uart.c +0 -0
index 7240ff7b5c24..8774d4bb43d7 100644

hw/char/exynos4210_uart.c static const MemoryRegionOps exynos4210_uart_ops = { · line 513

Quoted 8 lines
hw/char/exynos4210_uart.c +4 -0
@@ -506,6 +506,10 @@ static const MemoryRegionOps exynos4210_uart_ops = {
         .max_access_size = 4,
         .unaligned = false
     },
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
 };

This needs to come with more than just this as a commit message and change. What is a test case / situation that failed here? What does the data sheet say? Etc.

thanks
-- PMM

#41 lore raw

PATCH 33/63 hw/char/ibex_uart: prevent division by zero on baud rate calculation

In reply to Marc-André Lureau

Guard NANOSECONDS_PER_SECOND / baud with a zero check. The baud rate can be zero when the NCO field is zero or the input clock is not yet configured.

Fixes a7d2d98c5944 ("hw/char: Initial commit of Ibex UART")
Fixes 940aabb9f477 ("hw/char: Convert the Ibex UART to use the qdev Clock model")
---
 hw/char/ibex_uart.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
hw/char/ibex_uart.c +6 -2
index 26ed1aea140b..4c22fb4f58a8 100644
@@ -395,7 +395,9 @@ static void ibex_uart_write(void *opaque, hwaddr addr,
         if (value & R_CTRL_NCO_MASK) {
             uint64_t baud = ibex_uart_get_baud(s);
 
-            s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10;
+            if (baud) {
+                s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10;
+            }
         }
         break;
     case R_STATUS:
@@ -455,7 +457,9 @@ static void ibex_uart_clk_update(void *opaque, ClockEvent event)
     /* recompute uart's speed on clock change */
     uint64_t baud = ibex_uart_get_baud(s);
 
-    s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10;
+    if (baud) {
+        s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10;
+    }
 }
 
 static void fifo_trigger_update(void *opaque)
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by on v1 33/63
#42 lore raw

Re: [PATCH 33/63] hw/char/ibex_uart: prevent division by zero on baud rate calculation

Quoted 9 lines · Marc-André Lureau

Guard NANOSECONDS_PER_SECOND / baud with a zero check. The baud rate can be zero when the NCO field is zero or the input clock is not yet configured.

Fixes a7d2d98c5944 ("hw/char: Initial commit of Ibex UART")
Fixes 940aabb9f477 ("hw/char: Convert the Ibex UART to use the qdev

Clock model")

Alistair

Quoted 33 lines

---
 hw/char/ibex_uart.c | 8 ++++++--

 1 file changed, 6 insertions(+), 2 deletions(-)
hw/char/ibex_uart.c +0 -0
index 26ed1aea140b..4c22fb4f58a8 100644
@@ -395,7 +395,9 @@ static void ibex_uart_write(void *opaque, hwaddr
 addr,
          if (value & R_CTRL_NCO_MASK) {
              uint64_t baud = ibex_uart_get_baud(s);


-            s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10; +            if (baud) {
+                s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10;
+            }
         }
         break;
     case R_STATUS:

hw/char/ibex_uart.c +0 -0
@@ -455,7 +457,9 @@ static void ibex_uart_clk_update(void *opaque,
 ClockEvent event)
      /* recompute uart's speed on clock change */
      uint64_t baud = ibex_uart_get_baud(s);


-    s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10; +    if (baud) {
+        s->char_tx_time = (NANOSECONDS_PER_SECOND / baud) * 10; +    }
 }

 static void fifo_trigger_update(void *opaque)

#43 lore raw

PATCH 34/63 hw/char/imx_serial: update interrupts after status register writes

In reply to Marc-André Lureau

Writes to UCR2, USR1, and USR2 modify state that feeds into imx_update() but did not call it to re-evaluate the IRQ line. For instance, a guest clearing a status bit in USR1 (write-1-to-clear) would not deassert the corresponding interrupt.

Fixes 40b6f91151e7 ("i.MX: UART support")
---
 hw/char/imx_serial.c | 3 +++
 1 file changed, 3 insertions(+)
hw/char/imx_serial.c +3 -0
index 8ac4efbb5e98..7a3d575c964d 100644
@@ -324,12 +324,14 @@ static void imx_serial_write(void *opaque, hwaddr offset,
             }
         }
         s->ucr2 = value & 0xffff;
+        imx_update(s);
         break;
 
     case 0x25: /* USR1 */
         value &= USR1_AWAKE | USR1_AIRINT | USR1_DTRD | USR1_AGTIM |
                  USR1_FRAMERR | USR1_ESCF | USR1_RTSD | USR1_PARTYER;
         s->usr1 &= ~value;
+        imx_update(s);
         break;
 
     case 0x26: /* USR2 */
@@ -341,6 +343,7 @@ static void imx_serial_write(void *opaque, hwaddr offset,
                  USR2_RIDELT | USR2_IRINT | USR2_WAKE |
                  USR2_DCDDELT | USR2_RTSF | USR2_BRCD | USR2_ORE;
         s->usr2 &= ~value;
+        imx_update(s);
         break;
 
     /*
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#44 lore raw

PATCH 35/63 hw/char/serial: clamp zero baud rate to default

In reply to Marc-André Lureau

When baudbase is zero (e.g. not yet configured), the division baudbase / divider produces zero. This results in NANOSECONDS_PER_SECOND / speed yielding infinity, making char_transmit_time infinite and stalling transmission.

Fall back to the same 3500 baud default used for a zero divisor.

Fixes 96651db423a0 ("serial: add "baudbase" property")
---
 hw/char/serial.c | 3 +++
 1 file changed, 3 insertions(+)
hw/char/serial.c +3 -0
index 4339562ab003..44bf9fa0b25b 100644
@@ -178,6 +178,9 @@ static void serial_update_parameters(SerialState *s)
     frame_size += data_bits + stop_bits;
     /* Zero divisor should give about 3500 baud */
     speed = (s->divider == 0) ? 3500 : (float) s->baudbase / s->divider;
+    if (speed <= 0) {
+        speed = 3500;
+    }
     ssp.speed = speed;
     ssp.parity = parity;
     ssp.data_bits = data_bits;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#45 lore raw

PATCH 36/63 hw/char/sh_serial: fix RDF flag clear on FIFO reset

In reply to Marc-André Lureau

The FCR write handler cleared bit 1 of the status register (sr) instead of the SH_SERIAL_FLAG_RDF flag in the flags field. This meant the "receive data full" condition was never actually cleared when the guest reset the FIFO.

Fixes 63242a007a18 ("SH4: Serial controller improvement")
---
 hw/char/sh_serial.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/sh_serial.c +1 -1
index 10f96e3a44bc..30a22ea2d1c0 100644
@@ -175,7 +175,7 @@ static void sh_serial_write(void *opaque, hwaddr offs,
             }
             if (val & (1 << 1)) {
                 sh_serial_clear_fifo(s);
-                s->sr &= ~(1 << 1);
+                s->flags &= ~SH_SERIAL_FLAG_RDF;
             }
 
             return;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by on v1 36/63
#46 lore raw

Re: [PATCH 36/63] hw/char/sh_serial: fix RDF flag clear on FIFO reset

Quoted 30 lines · Marc-André Lureau

The FCR write handler cleared bit 1 of the status register (sr) instead of the SH_SERIAL_FLAG_RDF flag in the flags field. This meant the "receive data full" condition was never actually cleared when the guest reset the FIFO.

Fixes 63242a007a18 ("SH4: Serial controller improvement")
---
 hw/char/sh_serial.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/sh_serial.c +1 -1
index 10f96e3a44bc..30a22ea2d1c0 100644
@@ -175,7 +175,7 @@ static void sh_serial_write(void *opaque, hwaddr offs,
             }
             if (val & (1 << 1)) {
                 sh_serial_clear_fifo(s);
-                s->sr &= ~(1 << 1);
+                s->flags &= ~SH_SERIAL_FLAG_RDF;
             }
 
             return;
Signature · 2 lines
-- 
2.56.0.rc0.29.g47ce80527c56
Signature · 1 line
Yosinori Sato
#47 lore raw

PATCH 37/63 hw/char/sh_serial: use rx_cnt for available FIFO space

In reply to Marc-André Lureau

sh_serial_can_receive() used rx_head (the circular buffer write pointer) to compute available space. Since rx_head wraps around, this could overestimate or underestimate the remaining capacity. Use rx_cnt, which tracks the actual number of buffered bytes.

Fixes 543671d9907f ("hw/char/sh_serial: Return correct number of empty RX FIFO elements")
---
 hw/char/sh_serial.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/sh_serial.c +1 -1
index 30a22ea2d1c0..8728842b84e0 100644
@@ -316,7 +316,7 @@ static uint64_t sh_serial_read(void *opaque, hwaddr offs,
 
 static int sh_serial_can_receive(SHSerialState *s)
 {
-    return s->scr & (1 << 4) ? SH_RX_FIFO_LENGTH - s->rx_head : 0;
+    return s->scr & (1 << 4) ? SH_RX_FIFO_LENGTH - s->rx_cnt : 0;
 }
 
 static void sh_serial_receive_break(SHSerialState *s)
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by on v1 37/63
#48 lore raw

Re: [PATCH 37/63] hw/char/sh_serial: use rx_cnt for available FIFO space

Quoted 30 lines · Marc-André Lureau

sh_serial_can_receive() used rx_head (the circular buffer write pointer) to compute available space. Since rx_head wraps around, this could overestimate or underestimate the remaining capacity. Use rx_cnt, which tracks the actual number of buffered bytes.

Fixes 543671d9907f ("hw/char/sh_serial: Return correct number of empty RX FIFO elements")
---
 hw/char/sh_serial.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/sh_serial.c +1 -1
index 30a22ea2d1c0..8728842b84e0 100644
@@ -316,7 +316,7 @@ static uint64_t sh_serial_read(void *opaque, hwaddr offs,
 
 static int sh_serial_can_receive(SHSerialState *s)
 {
-    return s->scr & (1 << 4) ? SH_RX_FIFO_LENGTH - s->rx_head : 0;
+    return s->scr & (1 << 4) ? SH_RX_FIFO_LENGTH - s->rx_cnt : 0;
 }
 
 static void sh_serial_receive_break(SHSerialState *s)
Signature · 2 lines
-- 
2.56.0.rc0.29.g47ce80527c56
Signature · 1 line
Yosinori Sato
#49 lore raw

PATCH 38/63 hw/char/sh_serial: fix break detection flag

In reply to Marc-André Lureau

sh_serial_receive_break() set bit 4 of the status register (sr) instead of SH_SERIAL_FLAG_BRK (bit 3) in the flags field. The read path checks flags, not sr, so break events were never visible to the guest.

Fixes 63242a007a18 ("SH4: Serial controller improvement")
---
 hw/char/sh_serial.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/sh_serial.c +1 -1
index 8728842b84e0..8933af24be10 100644
@@ -322,7 +322,7 @@ static int sh_serial_can_receive(SHSerialState *s)
 static void sh_serial_receive_break(SHSerialState *s)
 {
     if (s->feat & SH_SERIAL_FEAT_SCIF) {
-        s->sr |= (1 << 4);
+        s->flags |= SH_SERIAL_FLAG_BRK;
     }
 }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by on v1 38/63
#50 lore raw

Re: [PATCH 38/63] hw/char/sh_serial: fix break detection flag

Quoted 29 lines · Marc-André Lureau

sh_serial_receive_break() set bit 4 of the status register (sr) instead of SH_SERIAL_FLAG_BRK (bit 3) in the flags field. The read path checks flags, not sr, so break events were never visible to the guest.

Fixes 63242a007a18 ("SH4: Serial controller improvement")
---
 hw/char/sh_serial.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/char/sh_serial.c +1 -1
index 8728842b84e0..8933af24be10 100644
@@ -322,7 +322,7 @@ static int sh_serial_can_receive(SHSerialState *s)
 static void sh_serial_receive_break(SHSerialState *s)
 {
     if (s->feat & SH_SERIAL_FEAT_SCIF) {
-        s->sr |= (1 << 4);
+        s->flags |= SH_SERIAL_FLAG_BRK;
     }
 }
 
Signature · 2 lines
-- 
2.56.0.rc0.29.g47ce80527c56
Signature · 1 line
Yosinori Sato
#51 lore raw

PATCH 39/63 hw/char/terminal3270: fix output buffer size for IAC-escaped header

In reply to Marc-André Lureau

The cmd byte prepended to outv can itself be IAC (0xFF), which insert_IAC_escape_char doubles. Worst case is 2 (escaped cmd) + 2048 (escaped 1024 data bytes) + 2 (IAC+IAC_EOR trailer) = 2052. The old size of 2051 could cause a 1-byte buffer overflow.

Fixes 2dc95b4cac5e ("s390x/3270: 3270 data stream handling")
---
 hw/char/terminal3270.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
hw/char/terminal3270.c +2 -2
index 989b6f6ee1e0..8247a07a54e6 100644
@@ -23,10 +23,10 @@
 /* Enough spaces for different window sizes. */
 #define INPUT_BUFFER_SIZE  1000
 /*
- * 1 for header, 1024*2 for datastream, 2 for tail
+ * 1*2 for header, 1024*2 for datastream, 2 for tail
  * Reserve enough spaces for telnet IAC escape.
  */
-#define OUTPUT_BUFFER_SIZE 2051
+#define OUTPUT_BUFFER_SIZE 2052
 
 struct Terminal3270 {
     EmulatedCcw3270Device cdev;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#52 lore raw

PATCH 40/63 hw/char/terminal3270: consume processed input data

In reply to Marc-André Lureau

read_payload_3270() decremented in_len after consuming bytes but never shifted the remaining data to the front of the buffer. Subsequent reads and appends in terminal_read (at &t->inv[t->in_len]) would reference wrong positions, re-processing stale bytes.

Add a memmove to compact the buffer after consuming a payload.

Fixes 2dc95b4cac5e ("s390x/3270: 3270 data stream handling")
---
 hw/char/terminal3270.c | 3 +++
 1 file changed, 3 insertions(+)
hw/char/terminal3270.c +3 -0
index 8247a07a54e6..506c7a77eac1 100644
@@ -205,6 +205,9 @@ static int read_payload_3270(EmulatedCcw3270Device *dev)
         return ret;
     }
     t->in_len -= len;
+    if (t->in_len > 0) {
+        memmove(t->inv, &t->inv[len], t->in_len);
+    }
 
     return len;
 }
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#53 lore raw

PATCH 41/63 hw/char/terminal3270: fix pre-handshake outbound data check

In reply to Marc-André Lureau

write_payload_3270() tried to allow telnet option negotiation through before the handshake by inspecting outv[0] and outv[1]. However, at this point the buffer has not been filled for the current call, so it inspected stale data from a previous write.

Telnet negotiation is handled at the chardev layer, not through the CCW device path, so unconditionally blocking outbound data before the handshake is correct.

Fixes e65a27209ca8 ("s390x/3270: Detect for continued presence of a 3270 client")
---
 hw/char/terminal3270.c | 8 +-------
 1 file changed, 1 insertion(+), 7 deletions(-)
hw/char/terminal3270.c +1 -7
index 506c7a77eac1..ad7f5d947291 100644
@@ -249,13 +249,7 @@ static int write_payload_3270(EmulatedCcw3270Device *dev, uint8_t cmd)
     int out_len = 0;
 
     if (!t->handshake_done) {
-        if (!(t->outv[0] == IAC && t->outv[1] != IAC)) {
-            /*
-             * Before having finished 3270 negotiation,
-             * sending outbound data except protocol options is prohibited.
-             */
-            return 0;
-        }
+        return 0;
     }
     if (!qemu_chr_fe_backend_connected(&t->chr)) {
         /* We just say we consumed all data if there's no backend. */
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#54 lore raw

PATCH 42/63 hw/char/virtio-serial-bus: validate scatter-gather state in post_load

In reply to Marc-André Lureau

After restoring a VirtQueueElement during migration, validate that iov_idx and iov_offset are within the bounds of the element's scatter-gather list. A corrupted migration stream could cause out-of-bounds access when the port is later unthrottled.

---
 hw/char/virtio-serial-bus.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/char/virtio-serial-bus.c +6 -0
index c36e18a4cfb5..8b9d5f32dea6 100644
@@ -768,6 +768,12 @@ static int fetch_active_ports_list(QEMUFile *f,
                 error_report("Failed to restore virtio-serial element");
                 return -EINVAL;
             }
+            if (port->iov_idx >= port->elem->out_num ||
+                port->iov_offset > port->elem->out_sg[port->iov_idx].iov_len) {
+                error_report("Invalid iov indexes");
+                g_clear_pointer(&port->elem, g_free);
+                return -EINVAL;
+            }
 
             /*
              *  Port was throttled on source machine.  Let's
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#55 lore raw

PATCH 43/63 hw/display/ramfb: validate guest-supplied stride

In reply to Marc-André Lureau

Validate the stride value provided by guest firmware before using it:
it must be at least linesize (otherwise scanlines overlap and the mapped region would be too small), 4-byte aligned (pixman requirement), and the stride*height product must not overflow INT_MAX (since pixman_image_get_stride returns int, used in the unmap callback).

Without these checks, a malicious guest can craft stride values that lead to undersized memory mappings or integer overflow.

Fixes 3fcf15df0073 ("ramfb: fix size calculation")
---
 hw/display/ramfb.c | 3 +++
 1 file changed, 3 insertions(+)
hw/display/ramfb.c +3 -0
index f477bdcc2186..2d5378754717 100644
@@ -63,6 +63,9 @@ static DisplaySurface *ramfb_create_display_surface(int width, int height,
     if (stride == 0) {
         stride = linesize;
     }
+    if (stride < linesize || stride % 4 != 0 || stride > INT_MAX / height) {
+        return NULL;
+    }
 
     mapsize = size = stride * (height - 1) + linesize;
     data = physical_memory_map(addr, &mapsize, false);
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#56 lore raw

PATCH 44/63 hw/display/ramfb: fix map/unmap region size mismatch

In reply to Marc-André Lureau

The map path computed the framebuffer size as stride*(height-1)+linesize, while the unmap callback in ramfb_unmap_display_surface used stride*height. This mismatch means we unmap more bytes than we mapped.

Fix the unmap callback to recompute linesize from the pixman image properties and use stride*(height-1)+linesize, matching the map path. The last scanline only occupies linesize bytes, so there is no need to map the trailing stride padding.

Fixes 3fcf15df0073 ("ramfb: fix size calculation")
---
 hw/display/ramfb.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
hw/display/ramfb.c +5 -2
index 2d5378754717..956c2660cb52 100644
@@ -41,8 +41,11 @@ struct RAMFBState {
 static void ramfb_unmap_display_surface(pixman_image_t *image, void *unused)
 {
     void *data = pixman_image_get_data(image);
-    uint32_t size = pixman_image_get_stride(image) *
-        pixman_image_get_height(image);
+    int stride = pixman_image_get_stride(image);
+    int height = pixman_image_get_height(image);
+    hwaddr linesize = pixman_image_get_width(image) *
+        PIXMAN_FORMAT_BPP(pixman_image_get_format(image)) / 8;
+    hwaddr size = (hwaddr)stride * (height - 1) + linesize;
     physical_memory_unmap(data, size, 0, 0);
 }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#57 lore raw

PATCH 45/63 hw/display/ssd0323: mask SPI data to 8 bits

In reply to Marc-André Lureau

The SSD0323 is an 8-bit SPI peripheral, but the transfer function receives a uint32_t. Mask the value to 8 bits before storing it as a command or command data, preventing upper bits from leaking into command dispatch and parameter values.

---
 hw/display/ssd0323.c | 1 +
 1 file changed, 1 insertion(+)
hw/display/ssd0323.c +1 -0
index 9309d4d10c4a..6172596abe6c 100644
@@ -102,6 +102,7 @@ static uint32_t ssd0323_transfer(SSIPeripheral *dev, uint32_t data)
         break;
     case SSD0323_CMD:
         DPRINTF("cmd 0x%02x\n", data);
+        data &= 0xff;
         if (s->cmd_len == 0) {
             s->cmd = data;
         } else {
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#58 lore raw

PATCH 46/63 hw/display/ssd0323: fix signed modulo in column/row commands

In reply to Marc-André Lureau

cmd_data is int32_t, so a negative value (possible via crafted migration state) would produce a negative result from the modulo operator under C99 semantics. This would set col or row to a negative index, causing out-of-bounds framebuffer access.

Cast to uint32_t before the modulo to guarantee a non-negative result.

Fixes e7f76c521f4f ("vmstateify ssd0323 display")
---
 hw/display/ssd0323.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
hw/display/ssd0323.c +4 -4
index 6172596abe6c..0a6f8cb686b3 100644
@@ -113,13 +113,13 @@ static uint32_t ssd0323_transfer(SSIPeripheral *dev, uint32_t data)
 #define DATA(x) if (s->cmd_len <= (x)) return 0
         case 0x15: /* Set column.  */
             DATA(2);
-            s->col = s->col_start = s->cmd_data[0] % 64;
-            s->col_end = s->cmd_data[1] % 64;
+            s->col = s->col_start = (uint32_t)s->cmd_data[0] % 64;
+            s->col_end = (uint32_t)s->cmd_data[1] % 64;
             break;
         case 0x75: /* Set row.  */
             DATA(2);
-            s->row = s->row_start = s->cmd_data[0] % 80;
-            s->row_end = s->cmd_data[1] % 80;
+            s->row = s->row_start = (uint32_t)s->cmd_data[0] % 80;
+            s->row_end = (uint32_t)s->cmd_data[1] % 80;
             break;
         case 0x81: /* Set contrast */
             DATA(1);
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#59 lore raw

PATCH 47/63 hw/display/xenfb: fix 24-bit pixel read in BLT macro

In reply to Marc-André Lureau

For depth == 24, each pixel is 3 bytes, but the BLT macro was using uint32_t as the source type, reading 4 bytes per pixel. The last pixel on the last row would read 1 byte past the framebuffer.

Read 24-bit pixels byte-by-byte instead, so the access stays within the 3-byte pixel boundary.

---
 hw/display/xenfb.c | 19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)
hw/display/xenfb.c +13 -6
index ae302b217fe9..10785e6843ae 100644
@@ -560,8 +560,13 @@ static int xenfb_configure_fb(struct XenFB *xenfb, size_t fb_len_lim,
     return 0;
 }
 
+static inline uint32_t read_pixel24(const uint8_t *p)
+{
+    return p[0] | (p[1] << 8) | (p[2] << 16);
+}
+
 /* A convenient function for munging pixels between different depths */
-#define BLT(SRC_T,DST_T,RSB,GSB,BSB,RDB,GDB,BDB)                        \
+#define BLT(SRC_T,DST_T,READ_PIX,RSB,GSB,BSB,RDB,GDB,BDB)               \
     for (line = y ; line < (y+h) ; line++) {                            \
         SRC_T *src = (SRC_T *)(xenfb->pixels                            \
                                + xenfb->offset                          \
@@ -584,7 +589,7 @@ static int xenfb_configure_fb(struct XenFB *xenfb, size_t fb_len_lim,
         const uint32_t GDM = (~0U) << (32 - GDB);                       \
         const uint32_t BDM = (~0U) << (32 - BDB);                       \
         for (col = x ; col < (x+w) ; col++) {                           \
-            uint32_t spix = *src;                                       \
+            uint32_t spix = READ_PIX(src);                              \
             *dst = (((spix << RSS) & RSM & RDM) >> RDS) |               \
                 (((spix << GSS) & GSM & GDM) >> GDS) |                  \
                 (((spix << BSS) & BSM & BDM) >> BDS);                   \
@@ -593,6 +598,8 @@ static int xenfb_configure_fb(struct XenFB *xenfb, size_t fb_len_lim,
         }                                                               \
     }
 
+#define READ_DEREF(p) (*(p))
+
 
 /*
  * This copies data from the guest framebuffer region, into QEMU's
@@ -612,18 +619,18 @@ static void xenfb_guest_copy(struct XenFB *xenfb, int x, int y, int w, int h)
         switch (xenfb->depth) {
         case 8:
             if (bpp == 16) {
-                BLT(uint8_t, uint16_t,   3, 3, 2,   5, 6, 5);
+                BLT(uint8_t, uint16_t, READ_DEREF, 3, 3, 2,  5, 6, 5);
             } else if (bpp == 32) {
-                BLT(uint8_t, uint32_t,   3, 3, 2,   8, 8, 8);
+                BLT(uint8_t, uint32_t, READ_DEREF, 3, 3, 2,  8, 8, 8);
             } else {
                 oops = 1;
             }
             break;
         case 24:
             if (bpp == 16) {
-                BLT(uint32_t, uint16_t,  8, 8, 8,   5, 6, 5);
+                BLT(uint8_t, uint16_t, read_pixel24, 8, 8, 8,  5, 6, 5);
             } else if (bpp == 32) {
-                BLT(uint32_t, uint32_t,  8, 8, 8,   8, 8, 8);
+                BLT(uint8_t, uint32_t, read_pixel24, 8, 8, 8,  8, 8, 8);
             } else {
                 oops = 1;
             }
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#60 lore raw

PATCH 48/63 hw/input/adb: reject zero-length requests

In reply to Marc-André Lureau

adb_request() accesses buf[0] unconditionally for tracing before processing the request. A zero-length buffer causes an out-of-bounds read. Return early with -1, which all callers already handle (they check for > 0 before using the result).

Fixes e590e7f01479 ("adb: add ADB bus trace events")
---
 hw/input/adb.c | 4 ++++
 1 file changed, 4 insertions(+)
hw/input/adb.c +4 -0
index 29c09c755966..7c67d2baa663 100644
@@ -96,6 +96,10 @@ int adb_request(ADBBusState *s, uint8_t *obuf, const uint8_t *buf, int len)
 {
     int ret;
 
+    if (len < 1) {
+        return -1;
+    }
+
     trace_adb_bus_request(buf[0] >> 4, adb_commands[buf[0] & 0xf], len);
 
     assert(s->autopoll_blocked);
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#61 lore raw

PATCH 49/63 hw/input/adb: validate devaddr on migration load

In reply to Marc-André Lureau

devaddr is used in 1 << d->devaddr bit shifts in do_adb_request() and adb_poll(). A crafted migration stream could set it to a value outside [0, MAX_ADB_DEVICES), causing undefined behavior.

Add a post_load validator to reject out-of-range values.

Fixes 0606b2883038 ("adb: introduce realize/unrealize and VMStateDescription for ADB bus")
---
 hw/input/adb.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
hw/input/adb.c +11 -0
index 7c67d2baa663..b6319fa31535 100644
@@ -280,10 +280,21 @@ static const TypeInfo adb_bus_type_info = {
     .class_init = adb_bus_class_init,
 };
 
+static int adb_device_post_load(void *opaque, int version_id)
+{
+    ADBDevice *d = opaque;
+
+    if (d->devaddr < 0 || d->devaddr >= MAX_ADB_DEVICES) {
+        return -EINVAL;
+    }
+    return 0;
+}
+
 const VMStateDescription vmstate_adb_device = {
     .name = "adb_device",
     .version_id = 0,
     .minimum_version_id = 0,
+    .post_load = adb_device_post_load,
     .fields = (const VMStateField[]) {
         VMSTATE_INT32(devaddr, ADBDevice),
         VMSTATE_INT32(handler, ADBDevice),
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#62 lore raw

PATCH 50/63 hw/input/adb: report error when too many devices are registered

In reply to Marc-André Lureau

adb_device_realizefn() returns early when the bus is full but does not set errp, so the caller has no way to know the device failed to realize. Set an error so the failure is properly propagated.

Fixes 0606b2883038 ("adb: introduce realize/unrealize and VMStateDescription for ADB bus")
---
 hw/input/adb.c | 2 ++
 1 file changed, 2 insertions(+)
hw/input/adb.c +2 -0
index b6319fa31535..54d00e2cd30c 100644
@@ -25,6 +25,7 @@
 #include "qemu/osdep.h"
 #include "hw/input/adb.h"
 #include "hw/core/qdev-properties.h"
+#include "qapi/error.h"
 #include "migration/vmstate.h"
 #include "qemu/module.h"
 #include "qemu/timer.h"
@@ -308,6 +309,7 @@ static void adb_device_realizefn(DeviceState *dev, Error **errp)
     ADBBusState *bus = ADB_BUS(qdev_get_parent_bus(dev));
 
     if (bus->nb_devices >= MAX_ADB_DEVICES) {
+        error_setg(errp, "Too many ADB devices");
         return;
     }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#63 lore raw

PATCH 51/63 hw/input/adb-kbd: validate WRITEREG request buffer length

In reply to Marc-André Lureau

The ADB_WRITEREG handler accesses buf[1] and buf[2] without checking that enough data was provided, allowing out-of-bounds reads from a short request buffer.

Add length checks before each access: require at least 2 bytes before reading buf[1], and exactly 3 bytes for register 3 commands that read buf[2].

Fixes 77cb0f5aafc8 ("Split adb.c into adb.c, adb-mouse.c and adb-kbd.c")
---
 hw/input/adb-kbd.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/input/adb-kbd.c +6 -0
index ece51d5df72b..9d80a3849b77 100644
@@ -241,12 +241,18 @@ static int adb_kbd_request(ADBDevice *d, uint8_t *obuf,
     olen = 0;
     switch (cmd) {
     case ADB_WRITEREG:
+        if (len < 2) {
+            return 0;
+        }
         trace_adb_device_kbd_writereg(reg, buf[1]);
         switch (reg) {
         case 2:
             /* LED status */
             break;
         case 3:
+            if (len != 3) {
+                return 0;
+            }
             switch (buf[2]) {
             case ADB_CMD_SELF_TEST:
                 break;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#64 lore raw

PATCH 52/63 hw/input/adb-kbd: validate ring buffer indices on migration load

In reply to Marc-André Lureau

A malicious or corrupted migration stream can supply out-of-range rptr, wptr, or count values for the keyboard ring buffer, leading to out-of-bounds accesses after load.

Add a post_load handler that rejects values outside the valid range of the data buffer.

Fixes 77cb0f5aafc8 ("Split adb.c into adb.c, adb-mouse.c and adb-kbd.c")
---
 hw/input/adb-kbd.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
hw/input/adb-kbd.c +13 -0
index 9d80a3849b77..8635354f024c 100644
@@ -334,10 +334,23 @@ static void adb_keyboard_event(DeviceState *dev, QemuConsole *src,
     adb_kbd_put_keycode(s, keycode);
 }
 
+static int adb_kbd_post_load(void *opaque, int version_id)
+{
+    KBDState *s = opaque;
+
+    if (s->rptr < 0 || s->rptr >= sizeof(s->data) ||
+        s->wptr < 0 || s->wptr >= sizeof(s->data) ||
+        s->count < 0 || s->count > sizeof(s->data)) {
+        return -EINVAL;
+    }
+    return 0;
+}
+
 static const VMStateDescription vmstate_adb_kbd = {
     .name = "adb_kbd",
     .version_id = 2,
     .minimum_version_id = 2,
+    .post_load = adb_kbd_post_load,
     .fields = (const VMStateField[]) {
         VMSTATE_STRUCT(parent_obj, KBDState, 0, vmstate_adb_device, ADBDevice),
         VMSTATE_BUFFER(data, KBDState),
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#65 lore raw

PATCH 53/63 hw/input/adb-kbd: check for errors after parent realize

In reply to Marc-André Lureau

adb_kbd_realizefn calls parent_realize but does not check for errors before continuing. When the caller passes errp as NULL, a failure is silently ignored and qemu_input_handler_register runs on a device that failed to realize.

Use ERRP_GUARD() and check *errp to properly detect and propagate errors regardless of the caller's errp value.

Fixes 77cb0f5aafc8 ("Split adb.c into adb.c, adb-mouse.c and adb-kbd.c")
---
 hw/input/adb-kbd.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/input/adb-kbd.c +6 -0
index 8635354f024c..d4a131dc1295 100644
@@ -24,6 +24,7 @@
 
 #include "qemu/osdep.h"
 #include "hw/input/adb.h"
+#include "qapi/error.h"
 #include "migration/vmstate.h"
 #include "qemu/module.h"
 #include "standard-headers/linux/input-event-codes.h"
@@ -385,7 +386,12 @@ static void adb_kbd_realizefn(DeviceState *dev, Error **errp)
     KBDState *s = ADB_KEYBOARD(dev);
     ADBKeyboardClass *akc = ADB_KEYBOARD_GET_CLASS(dev);
 
+    ERRP_GUARD();
+
     akc->parent_realize(dev, errp);
+    if (*errp) {
+        return;
+    }
     s->hs = qemu_input_handler_register(dev, &adb_keyboard_handler);
 }
 
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#66 lore raw

PATCH 54/63 hw/input/adb-kbd: guard parent_unrealize against NULL

In reply to Marc-André Lureau

parent_unrealize is NULL since neither ADBDeviceClass nor DeviceClass sets dc->unrealize. Guard the call to prevent a NULL dereference during device teardown.

Fixes 6a935957d60e ("hw/input: keep QemuInputHandlerState in adb-kbd")
---
 hw/input/adb-kbd.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
hw/input/adb-kbd.c +3 -1
index d4a131dc1295..43c0ead60c59 100644
@@ -401,7 +401,9 @@ static void adb_kbd_unrealizefn(DeviceState *dev)
     ADBKeyboardClass *akc = ADB_KEYBOARD_GET_CLASS(dev);
 
     g_clear_pointer(&s->hs, qemu_input_handler_unregister);
-    akc->parent_unrealize(dev);
+    if (akc->parent_unrealize) {
+        akc->parent_unrealize(dev);
+    }
 }
 
 static void adb_kbd_initfn(Object *obj)
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#67 lore raw

PATCH 55/63 hw/input/adb-mouse: validate WRITEREG request buffer length

In reply to Marc-André Lureau

The ADB_WRITEREG handler accesses buf[1] without checking that enough data was provided, allowing an out-of-bounds read from a short request buffer.

Add a length check requiring at least 2 bytes before reading buf[1].

Fixes 267002cd2831 ("CUDA + ADB support")
---
 hw/input/adb-mouse.c | 3 +++
 1 file changed, 3 insertions(+)
hw/input/adb-mouse.c +3 -0
index 5dcdc851fcdf..80584cce1c6b 100644
@@ -164,6 +164,9 @@ static int adb_mouse_request(ADBDevice *d, uint8_t *obuf,
     olen = 0;
     switch (cmd) {
     case ADB_WRITEREG:
+        if (len < 2) {
+            return 0;
+        }
         trace_adb_device_mouse_writereg(reg, buf[1]);
         switch (reg) {
         case 2:
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#68 lore raw

PATCH 56/63 hw/input/adb-mouse: check for errors after parent realize

In reply to Marc-André Lureau

adb_mouse_realizefn calls parent_realize but does not check for errors before continuing. When the caller passes errp as NULL, a failure is silently ignored and qemu_input_handler_register runs on a device that failed to realize.

Use ERRP_GUARD() and check *errp to properly detect and propagate errors regardless of the caller's errp value.

Fixes 2e4a7c9c5df4 ("adb: QOM'ify ADB devices")
---
 hw/input/adb-mouse.c | 6 ++++++
 1 file changed, 6 insertions(+)
hw/input/adb-mouse.c +6 -0
index 80584cce1c6b..f9f989930ba1 100644
@@ -25,6 +25,7 @@
 #include "qemu/osdep.h"
 #include "ui/console.h"
 #include "hw/input/adb.h"
+#include "qapi/error.h"
 #include "migration/vmstate.h"
 #include "qemu/module.h"
 #include "adb-internal.h"
@@ -274,7 +275,12 @@ static void adb_mouse_realizefn(DeviceState *dev, Error **errp)
     MouseState *s = ADB_MOUSE(dev);
     ADBMouseClass *amc = ADB_MOUSE_GET_CLASS(dev);
 
+    ERRP_GUARD();
+
     amc->parent_realize(dev, errp);
+    if (*errp) {
+        return;
+    }
 
     s->hs = qemu_input_handler_register(dev, &adb_mouse_handler);
 }
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#69 lore raw

PATCH 57/63 hw/input/adb-mouse: add unrealize handler to unregister input

In reply to Marc-André Lureau

The mouse device registers a QemuInputHandler during realize but never unregisters it, leaking the handler on device removal.

Add an unrealize handler that calls qemu_input_handler_unregister and chains to parent_unrealize when present.

Fixes 118e15191800 ("hw/input/adb-mouse: convert to use QemuInputHandler")
---
 hw/input/adb-mouse.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
hw/input/adb-mouse.c +14 -0
index f9f989930ba1..0f2ecf0fd88c 100644
@@ -51,6 +51,7 @@ struct ADBMouseClass {
     /*< private >*/
 
     DeviceRealize parent_realize;
+    DeviceUnrealize parent_unrealize;
 };
 
 #define ADB_MOUSE_BUTTON_LEFT   0x01
@@ -285,6 +286,17 @@ static void adb_mouse_realizefn(DeviceState *dev, Error **errp)
     s->hs = qemu_input_handler_register(dev, &adb_mouse_handler);
 }
 
+static void adb_mouse_unrealizefn(DeviceState *dev)
+{
+    MouseState *s = ADB_MOUSE(dev);
+    ADBMouseClass *amc = ADB_MOUSE_GET_CLASS(dev);
+
+    g_clear_pointer(&s->hs, qemu_input_handler_unregister);
+    if (amc->parent_unrealize) {
+        amc->parent_unrealize(dev);
+    }
+}
+
 static void adb_mouse_initfn(Object *obj)
 {
     ADBDevice *d = ADB_DEVICE(obj);
@@ -300,6 +312,8 @@ static void adb_mouse_class_init(ObjectClass *oc, const void *data)
 
     device_class_set_parent_realize(dc, adb_mouse_realizefn,
                                     &amc->parent_realize);
+    device_class_set_parent_unrealize(dc, adb_mouse_unrealizefn,
+                                      &amc->parent_unrealize);
     set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
 
     adc->devreq = adb_mouse_request;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#70 lore raw

PATCH 58/63 hw/input/hid: validate queue length and key count on migration load

In reply to Marc-André Lureau

A malicious or corrupted migration stream can supply an out-of-range queue head, queue length, or keyboard key count, leading to out-of-bounds accesses after load.

Validate that s->head is within the queue bounds, that s->n does not exceed QUEUE_LENGTH, and that s->kbd.keys stays within the key[] array bounds before any post_load processing.

Fixes ccd4ed065be4 ("hid: introduce hid vmstate macros")
---
 hw/input/hid.c | 7 +++++++
 1 file changed, 7 insertions(+)
hw/input/hid.c +7 -0
index 0f28827554e3..5098497f41bb 100644
@@ -547,6 +547,13 @@ static int hid_post_load(void *opaque, int version_id)
 {
     HIDState *s = opaque;
 
+    if (s->head >= QUEUE_LENGTH || s->n > QUEUE_LENGTH) {
+        return -EINVAL;
+    }
+    if (s->kind == HID_KEYBOARD &&
+        (s->kbd.keys < 0 || s->kbd.keys > ARRAY_SIZE(s->kbd.key))) {
+        return -EINVAL;
+    }
     hid_set_next_idle(s);
 
     if (s->n == QUEUE_LENGTH && (s->kind == HID_TABLET ||
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#71 lore raw

PATCH 59/63 hw/input/hid: fix off-by-one in pointer queue access on migration load

In reply to Marc-André Lureau

The post_load handler reads the last queued pointer event at index head+n, but in a circular queue with head as the first element and n elements, the last valid entry is at head+n-1. When n equals QUEUE_LENGTH (16), head+n wraps to head, reading the oldest entry instead of the newest.

Fixes ba4d26064e8c ("hid: handle full ptr queues in post_load")
---
 hw/input/hid.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/input/hid.c +1 -1
index 5098497f41bb..847eac97cbe8 100644
@@ -567,7 +567,7 @@ static int hid_post_load(void *opaque, int version_id)
          * mouse.
          */
         HIDPointerEvent evt;
-        evt = s->ptr.queue[(s->head+s->n) & QUEUE_MASK];
+        evt = s->ptr.queue[(s->head + s->n - 1) & QUEUE_MASK];
         if (s->kind == HID_MOUSE) {
             evt.xdx = 0;
             evt.ydy = 0;
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#72 lore raw

PATCH 60/63 hw/input/pl050: remove duplicate class_init assignment

In reply to Marc-André Lureau

The .class_init field was set twice in the TypeInfo struct.

---
 hw/input/pl050.c | 1 -
 1 file changed, 1 deletion(-)
hw/input/pl050.c +0 -1
index 48df2734e269..3731e6969850 100644
@@ -265,7 +265,6 @@ static const TypeInfo pl050_type_info = {
     .class_init    = pl050_class_init,
     .class_size    = sizeof(PL050DeviceClass),
     .abstract      = true,
-    .class_init    = pl050_class_init,
 };
 
 static void pl050_register_types(void)
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
Reviewed-by on v1 60/63
#73 lore raw

Re: [PATCH 60/63] hw/input/pl050: remove duplicate class_init assignment

Quoted 4 lines · Marc-André Lureau

The .class_init field was set twice in the TypeInfo struct.

Fixes 475a4d463b2 ("pl050: introduce PL050DeviceClass")
Quoted 17 lines
---
  hw/input/pl050.c | 1 -
  1 file changed, 1 deletion(-)
hw/input/pl050.c +0 -1
index 48df2734e269..3731e6969850 100644
@@ -265,7 +265,6 @@ static const TypeInfo pl050_type_info = {
      .class_init    = pl050_class_init,
      .class_size    = sizeof(PL050DeviceClass),
      .abstract      = true,
-    .class_init    = pl050_class_init,
  };
 
  static void pl050_register_types(void)
#74 lore raw

PATCH 61/63 hw/input/stellaris_gamepad: deassert IRQs on reset

In reply to Marc-André Lureau

The reset handler clears the pressed state but does not deassert the IRQ outputs. If a button was pressed before reset, its IRQ line remains high even though the internal state shows it as released.

Deassert all IRQ lines during reset to keep GPIO state consistent with the pressed array.

Fixes a75f336b97a6 ("hw/input/stellaris_input: Convert to qdev")
---
 hw/input/stellaris_gamepad.c | 3 +++
 1 file changed, 3 insertions(+)
hw/input/stellaris_gamepad.c +3 -0
index 376d91abad70..90780613069e 100644
@@ -76,6 +76,9 @@ static void stellaris_gamepad_reset_enter(Object *obj, ResetType type)
     StellarisGamepad *s = STELLARIS_GAMEPAD(obj);
 
     memset(s->pressed, 0, s->num_buttons * sizeof(uint8_t));
+    for (uint32_t i = 0; i < s->num_buttons; i++) {
+        qemu_set_irq(s->irqs[i], 0);
+    }
 }
 
 static const Property stellaris_gamepad_properties[] = {
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#75 lore raw

PATCH 62/63 hw/input/virtio-input: free VirtQueueElement in error unwind path

In reply to Marc-André Lureau

When virtqueue_pop fails partway through a batch, the unwind loop calls virtqueue_unpop on already-popped elements but does not free them. Each VirtQueueElement was allocated by virtqueue_pop and must be freed by the caller.

Add g_free after virtqueue_unpop to prevent the leak.

Fixes 57094547dfea ("virtio-input: fix eventq batching")
---
 hw/input/virtio-input.c | 1 +
 1 file changed, 1 insertion(+)
hw/input/virtio-input.c +1 -0
index 6494cfbbe82d..dfd2964ae122 100644
@@ -49,6 +49,7 @@ void virtio_input_send(VirtIOInput *vinput, virtio_input_event *event)
         if (!elem) {
             while (--i >= 0) {
                 virtqueue_unpop(vinput->evt, vinput->queue[i].elem, 0);
+                g_free(vinput->queue[i].elem);
             }
             vinput->qindex = 0;
             trace_virtio_input_queue_full();
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56
#76 lore raw

PATCH 63/63 hw/input/virtio-input: document queue preservation on device reset

In reply to Marc-André Lureau

The queue and qindex are host-side input event buffering, not device state. They accumulate events until a SYN_REPORT is received, at which point they are delivered to the guest. The elem pointers are only live within a single virtio_input_send call, so there is no stale pointer issue across reset.

Add a comment documenting this intentional design.

---
 hw/input/virtio-input.c | 4 ++++
 1 file changed, 4 insertions(+)
hw/input/virtio-input.c +4 -0
index dfd2964ae122..aefe02d14ef3 100644
@@ -217,6 +217,10 @@ static void virtio_input_reset(VirtIODevice *vdev)
             vic->change_active(vinput);
         }
     }
+    /*
+     * Don't reset qindex: the queue holds host-side input events
+     * not yet batched (no SYN_REPORT yet), not device state.
+     */
 }
 
 static int virtio_input_post_load(void *opaque, int version_id)
Signature · 1 line
2.56.0.rc0.29.g47ce80527c56