[PATCH] generic_block_fiemap: fix integer overflow

From: Mikulas Patocka
Date: Mon Oct 10 2016 - 14:12:58 EST


In the function __generic_block_fiemap, the variable len has type loff_t
and the variable map_bh.b_size has type size_t. On 32-bit kernels, the
assignment "map_bh.b_size = len" can overflow to 0 if the file size is
divisible by 2^32.

On gfs2, this overflow causes BUG_ON(maxlen == 0) in gfs2_block_map. On
ext2, it causes contiguous allocated space being incorrectly reported as
a list of one-block extents.

Generally, the loop in __generic_block_fiemap doesn't look much sensible
at all:
* At first iteration, we try to map len bytes at start_blk
* At next iteration, we advance start_blk, but we leave len unchanged - so
len now points beyond file end - so, what's the point of limiting the
mapping size to "len" anyway?

For example, if we had a file that has one real block and 10 preallocated
blocks beyond i_size, the loop would incorrectly report 11 extents even if
all 11 blocks were contiguous (due to limiting the query size to "len").

This patch uses the maximum b_size (-1UL << inode->i_blkbits)
unconditionally, so that we always report extents as big as possible. It
fixes the crash in gfs2 and discrepancies in ext2.

Signed-off-by: Mikulas Patocka <mikulas@xxxxxxxxxxxxxxxxxxxxxxxx>
Cc: stable@xxxxxxxxxxxxxxx

---
fs/ioctl.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

Index: linux-2.6/fs/ioctl.c
===================================================================
--- linux-2.6.orig/fs/ioctl.c
+++ linux-2.6/fs/ioctl.c
@@ -312,7 +312,7 @@ int __generic_block_fiemap(struct inode
* many contiguous blocks as possible at once
*/
memset(&map_bh, 0, sizeof(struct buffer_head));
- map_bh.b_size = len;
+ map_bh.b_size = -1UL << inode->i_blkbits;

ret = get_block(inode, start_blk, &map_bh, 0);
if (ret)