From: David Woodhouse When the grant's target page cannot be mapped, the failure path calls gnt_unref(), which asserts that the map_track[] refcount is non-zero — but the refcount was only incremented after a successful mapping. Take the reference as soon as gnt_ref() succeeds, so the failure path stays balanced. Refuse writable mappings, including a write upgrade of an existing mapping, when the underlying memory region is read-only, and set errno when the upgrade fails. Fixes: b08d88e30f06 ("hw/xen: Add emulated implementation of grant table operations") Reported-by: Hui Peng Closes: https://gitlab.com/qemu-project/qemu/-/work_items/4525 Signed-off-by: David Woodhouse --- hw/i386/kvm/xen_gnttab.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/hw/i386/kvm/xen_gnttab.c b/hw/i386/kvm/xen_gnttab.c index 85b324e62d0..26d1febac4d 100644 --- a/hw/i386/kvm/xen_gnttab.c +++ b/hw/i386/kvm/xen_gnttab.c @@ -363,7 +363,9 @@ static void *xen_be_gnttab_map_refs(struct xengntdev_handle *xgt, act = g_hash_table_lookup(xgt->active_maps, GINT_TO_POINTER(refs[0])); if (act) { if ((prot & PROT_WRITE) && !(act->prot & PROT_WRITE)) { - if (gnt_ref(s, refs[0], prot) == INVALID_GPA) { + if (act->mrs.readonly || + gnt_ref(s, refs[0], prot) == INVALID_GPA) { + errno = EINVAL; return NULL; } act->prot |= PROT_WRITE; @@ -376,12 +378,19 @@ static void *xen_be_gnttab_map_refs(struct xengntdev_handle *xgt, return NULL; } + /* + * Keep the map_track[] count balanced with the gnt_unref() in the + * failure path below, which asserts that it never underflows. + */ + s->map_track[refs[0]]++; + act = g_new0(struct active_ref, 1); act->prot = prot; act->refcnt = 1; act->mrs = memory_region_find(get_system_memory(), gpa, XEN_PAGE_SIZE); if (act->mrs.mr && + !(act->mrs.readonly && (prot & PROT_WRITE)) && !int128_lt(act->mrs.size, int128_make64(XEN_PAGE_SIZE)) && memory_region_get_ram_addr(act->mrs.mr) != RAM_ADDR_INVALID) { act->virtaddr = qemu_map_ram_ptr(act->mrs.mr->ram_block, @@ -394,7 +403,6 @@ static void *xen_be_gnttab_map_refs(struct xengntdev_handle *xgt, return NULL; } - s->map_track[refs[0]]++; g_hash_table_insert(xgt->active_maps, GINT_TO_POINTER(refs[0]), act); } -- 2.43.0