Commit 6345efb9f3 for qemu.org
commit 6345efb9f3fa0217ad7fe5ea34184524023b149c
Author: Peter Maydell <peter.maydell@linaro.org>
Date: Thu Nov 19 14:03:37 2026 +0000
block/qcow2: Detect corrupt images where first refcount block is empty
In a QCOW2 image, the header is always cluster zero, and so that
cluster must have a non-zero refcount. This means that an image
where the first entry in the refcount table is zero, or where it
points to a refblock which is empty, must be corrupt. Detect this in
alloc_refblock().
This fixes a bug where 'qemu-img amend -o refcount_bits=...' would
crash on a corrupted image where the entire refcount table was empty.
The crash happened because walk_over_reftable() would return with
new_reftable_size == 0 and new_reftable == NULL.
qcow2_change_refcount_table() updated s->refcount_table and
s->refcount_table_size with these bogus values, and
update_max_refcount_table_index() would crash trying to dereference
NULL[UINT_MAX]. We add a defensive assertion here that the
new refcount table isn't zero-sized; this can't be reached because
it only happens in the corruption case that we now detect.
Cc: qemu-stable@nongnu.org
Fixes: 791c9a004efbcff ("qcow2: Add function for refcount order amendment")
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3690
Reported-by: a1gxer
Suggested-by: Kevin Wolf <kwolf@redhat.com>
Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
Message-ID: <20261119140338.2918386-2-peter.maydell@linaro.org>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Kevin Wolf <kwolf@redhat.com>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
diff --git a/block/qcow2-refcount.c b/block/qcow2-refcount.c
index df7f6d2f23..2102386147 100644
--- a/block/qcow2-refcount.c
+++ b/block/qcow2-refcount.c
@@ -3139,6 +3139,14 @@ alloc_refblock(BlockDriverState *bs, uint64_t **reftable,
BDRVQcow2State *s = bs->opaque;
int64_t offset;
+ if (reftable_index == 0 && refblock_empty) {
+ /* The header is in cluster 0 so it must have a non-zero refcount */
+ qcow2_signal_corruption(bs, true, -1, -1,
+ "first refblock is empty");
+ error_setg(errp, "Image is corrupt (first refblock is empty)");
+ return -EIO;
+ }
+
if (!refblock_empty && reftable_index >= *reftable_size) {
uint64_t *new_reftable;
uint64_t new_reftable_size;
@@ -3451,6 +3459,13 @@ int qcow2_change_refcount_order(BlockDriverState *bs, int refcount_order,
}
} while (new_allocation);
+ /*
+ * This can only happen if the reftable is all zeroes, but the header is
+ * in cluster 0 and must have a non-zero refcount, and we check that in
+ * alloc_refblock().
+ */
+ assert(new_reftable_size != 0);
+
/* Second, write the new refblocks */
ret = walk_over_reftable(bs, &new_reftable, &new_reftable_index,
&new_reftable_size, new_refblock,