Skip to content

Commit

Permalink
Avoid SIGBUS on mmap failure
Browse files Browse the repository at this point in the history
mmap will fail with SIGBUS if trying to map a non-existent portion of
a file. While this should never happen with /dev/mem, it can happen if
passing a regular file with option -d. While people should no longer
do that, failure gracefully seems better than crashing. So check for
the file size before calling mmap.

This closes bug #46066:
http://savannah.nongnu.org/bugs/?46066
  • Loading branch information
jdelvare committed Oct 14, 2015
1 parent 33b5aaf commit c081fa4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
2015-10-14 Jean Delvare <jdelvare@suse.de>

* util.c: Avoid SIGBUS on mmap failure.
This fixes Savannah bug #46066:
https://savannah.nongnu.org/bugs/?46066

2015-10-01 Roy Franz <roy.franz@linaro.org>

* dmiopt.c: Add "--no-sysfs" option description to -h output.
Expand Down
21 changes: 21 additions & 0 deletions util.c
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ void *mem_chunk(off_t base, size_t len, const char *devmem)
void *p;
int fd;
#ifdef USE_MMAP
struct stat statbuf;
off_t mmoffset;
void *mmp;
#endif
Expand All @@ -169,6 +170,26 @@ void *mem_chunk(off_t base, size_t len, const char *devmem)
}

#ifdef USE_MMAP
if (fstat(fd, &statbuf) == -1)
{
fprintf(stderr, "%s: ", devmem);
perror("stat");
free(p);
return NULL;
}

/*
* mmap() will fail with SIGBUS if trying to map beyond the end of
* the file.
*/
if (S_ISREG(statbuf.st_mode) && base + (off_t)len > statbuf.st_size)
{
fprintf(stderr, "mmap: Can't map beyond end of file %s\n",
devmem);
free(p);
return NULL;
}

#ifdef _SC_PAGESIZE
mmoffset = base % sysconf(_SC_PAGESIZE);
#else
Expand Down

0 comments on commit c081fa4

Please sign in to comment.