]> git.hungrycats.org Git - btrfs-progs/commitdiff
btrfs-progs: fix-data-checksum: fix the size of the error mirror bitmap
authorSidong Yang <sidong.yang@furiosa.ai>
Tue, 4 Aug 2026 12:36:17 +0000 (12:36 +0000)
committerDavid Sterba <dsterba@suse.com>
Mon, 17 Aug 2026 13:10:10 +0000 (15:10 +0200)
[BUG]
Running "btrfs rescue fix-data-checksum" on a filesystem with a data
checksum mismatch triggers a heap buffer overflow:

  ==3692==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000190
  READ of size 8 at 0x502000000190 thread T0
      #0 set_bit kernel-lib/bitops.h:32
      #1 add_corrupted_block cmds/rescue-fix-data-checksum.c:99
      #2 verify_one_data_block cmds/rescue-fix-data-checksum.c:143
      #3 iterate_one_csum_item cmds/rescue-fix-data-checksum.c:178
      #4 iterate_csum_root cmds/rescue-fix-data-checksum.c:252
      #5 btrfs_recover_fix_data_checksum cmds/rescue-fix-data-checksum.c:510
  0x502000000191 is located 0 bytes after 1-byte region [0x502000000190,0x502000000191)
  allocated by thread T0 here:
      #0 calloc
      #1 add_corrupted_block cmds/rescue-fix-data-checksum.c:94

[CAUSE]
BITS_TO_LONGS() returns the number of unsigned longs needed to hold the
given amount of bits, not the number of bytes. But the value is passed as
the byte size to calloc():

  last->error_mirror_bitmap = calloc(1, BITS_TO_LONGS(num_mirrors));

For any sane number of mirrors this allocates a single byte, while
set_bit() accesses the bitmap in unsigned long units, thus reading and
writing 8 bytes out of a 1 byte allocation.

[FIX]
Use bitmap_zalloc() from kernel-lib/bitmap.h, which does the size
calculation for the caller, and pair it with bitmap_free() when the
record is released.

Fixes: 0e999c9bd3e7 ("btrfs-progs: introduce "btrfs rescue fix-data-checksum"")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Sidong Yang <sidong.yang@furiosa.ai>
Signed-off-by: David Sterba <dsterba@suse.com>
cmds/rescue-fix-data-checksum.c

index a4bf4c0660880b4d69d4d0f55322ef862072268c..d0cec4c9028bfbe3a3ef81db3a3c4259b4484264 100644 (file)
@@ -16,6 +16,7 @@
 
 #include "kerncompat.h"
 #include <ctype.h>
+#include "kernel-lib/bitmap.h"
 #include "kernel-shared/disk-io.h"
 #include "kernel-shared/ctree.h"
 #include "kernel-shared/volumes.h"
@@ -91,7 +92,7 @@ add:
        last = calloc(1, sizeof(*last));
        if (!last)
                return -ENOMEM;
-       last->error_mirror_bitmap = calloc(1, BITS_TO_LONGS(num_mirrors));
+       last->error_mirror_bitmap = bitmap_zalloc(num_mirrors);
        if (!last->error_mirror_bitmap) {
                free(last);
                return -ENOMEM;
@@ -456,7 +457,7 @@ static void free_corrupted_blocks(void)
 
                entry = list_entry(corrupted_blocks.next, struct corrupted_block, list);
                list_del_init(&entry->list);
-               free(entry->error_mirror_bitmap);
+               bitmap_free(entry->error_mirror_bitmap);
                free(entry);
        }
 }