Skip to content

Commit 3604885

Browse files
rientjestorvalds
authored andcommitted
debugfs: fix race in u32_array_read and allocate array at open
u32_array_open() is racy when multiple threads read from a file with a seek position of zero, i.e. when two or more simultaneous reads are occurring after the non-seekable files are created. It is possible that file->private_data is double-freed because the threads races between kfree(file->private-data); and file->private_data = NULL; The fix is to only do format_array_alloc() when the file is opened and free it when it is closed. Note that because the file has always been non-seekable, you can't open it and read it multiple times anyway, so the data has always been generated just once. The difference is that now it is generated at open time rather than at the time of the first read, and that avoids the race. Reported-by: Dave Jones <davej@redhat.com> Acked-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Tested-by: Raghavendra <raghavendra.kt@linux.vnet.ibm.com> Signed-off-by: David Rientjes <rientjes@google.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
1 parent c46de22 commit 3604885

1 file changed

Lines changed: 11 additions & 22 deletions

File tree

‎fs/debugfs/file.c‎

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -526,12 +526,6 @@ struct array_data {
526526
u32 elements;
527527
};
528528

529-
static int u32_array_open(struct inode *inode, struct file *file)
530-
{
531-
file->private_data = NULL;
532-
return nonseekable_open(inode, file);
533-
}
534-
535529
static size_t format_array(char *buf, size_t bufsize, const char *fmt,
536530
u32 *array, u32 array_size)
537531
{
@@ -573,26 +567,21 @@ static char *format_array_alloc(const char *fmt, u32 *array,
573567
return ret;
574568
}
575569

576-
static ssize_t u32_array_read(struct file *file, char __user *buf, size_t len,
577-
loff_t *ppos)
570+
static int u32_array_open(struct inode *inode, struct file *file)
578571
{
579-
struct inode *inode = file->f_path.dentry->d_inode;
580572
struct array_data *data = inode->i_private;
581-
size_t size;
582573

583-
if (*ppos == 0) {
584-
if (file->private_data) {
585-
kfree(file->private_data);
586-
file->private_data = NULL;
587-
}
588-
589-
file->private_data = format_array_alloc("%u", data->array,
590-
data->elements);
591-
}
574+
file->private_data = format_array_alloc("%u", data->array,
575+
data->elements);
576+
if (!file->private_data)
577+
return -ENOMEM;
578+
return nonseekable_open(inode, file);
579+
}
592580

593-
size = 0;
594-
if (file->private_data)
595-
size = strlen(file->private_data);
581+
static ssize_t u32_array_read(struct file *file, char __user *buf, size_t len,
582+
loff_t *ppos)
583+
{
584+
size_t size = strlen(file->private_data);
596585

597586
return simple_read_from_buffer(buf, len, ppos,
598587
file->private_data, size);

0 commit comments

Comments
 (0)