Re: [PATCH] check mapped ranges on sysfs resource files (for 2.6.27)

From: Jesse Barnes
Date: Thu Oct 02 2008 - 19:51:52 EST


On Thursday, October 2, 2008 4:30 pm Linus Torvalds wrote:
> On Thu, 2 Oct 2008, Jesse Barnes wrote:
> > + unsigned long map_len = vma->vm_end - vma->vm_start;
> > + unsigned long map_offset = vma->vm_pgoff << PAGE_SHIFT;
>
> This seems broken for big vm_pgoff values, where that shift will
> potentially overflow, no?

Ah yes, exactly what we want to be checking for in fact.

> Also, it strikes me that we don't seem to check that the resource start is
> page-aligned. We just do
>
> vma->vm_pgoff += start >> PAGE_SHIFT;
>
> without checking if we just dropped low bits from 'start'.

Hm, yeah looks like that's a long standing issue...

> Of course, if the length of the resource is bigger than a page, I guess
> the resource is guaranteed to be at least page-aligned, so maybe the
> length check - if it was correct - would be sufficient.
>
> Anyway, it would be *much* better to do the length check in pages rather
> than in bytes, to avoid the overflow condition.
>
> Can somebody test if something like this works? It also prints the actual
> name of the device, not just a random BAR number (but it will print
> everyting in PFN's, I hate potentially losing information).

Yeah, looks much better. I was using this silly test program to see if the
earlier code worked. Just pass in both valid and invalid sizes.

Jesse
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
size_t len;
int fd;
void *ptr;

if (argc != 3) {
fprintf(stderr, "usage: %s <file> <mapsize>\n",
argv[0]);
return -1;
}

len = atoi(argv[2]);

fd = open(argv[1], O_RDONLY);
if (fd == -1) {
fprintf(stderr, "open failed: %s\n", strerror(errno));
return errno;
}

ptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
fprintf(stderr, "mmap failed: %s\n", strerror(errno));
return errno;
}

printf("mmap of %s with size %zd succeeded\n", argv[1], len);

munmap(ptr, len); /* ignore any errors, we don't care */
close(fd);
return 0;
}