Skip to contentSkip to conversation

mmap

DISCUSSION Sébastien Paumier 2 participants 2 messages Dec 2, 2011

lore
Share & tools
lore
#0 lore raw

Hi,
I have a question about mmap's behavior when one tries to map a file asking for a length greater than the actual file size. When I run the attached code on a 100 bytes file, I have the following output:

(... file content followed by zeros...)
n=4096
write: Bad address

So, it seems that the actual memory area provided by mmap is one page large and not the requested length of filesize+10000. I guess that 'write' writes less than requested because it was interrupted by the SIGBUS signal. And my question is:

shouldn't mmap either complain about the requested length or provide an accessible area of the requested length, instead of silently failing ?

Best regards,
Sébastien Paumier

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#include <errno.h>

int main(int argc, char* argv[]){

if(argc != 2) {
	fprintf(stderr,"Usage: %s <file>\n",argv[0]);
	exit(1);
}
int fd = open(argv[argc-1],O_RDONLY);
if (fd==-1) {
	perror("open");
	return 1;
}
struct stat status;
if(-1 == fstat(fd,&status)){
	perror("fstat");
	return 1;
}
char* mem=(char*) mmap(NULL, status.st_size+10000, PROT_READ, MAP_PRIVATE,fd,0);
if(mem == MAP_FAILED){
	perror("mmap");
	return 1;
}
int n;
if ( -1 == (n=write(1,mem, status.st_size+10000))) {
	perror("write");
	return 1;
}
printf("\nn=%d\n",n);
if( -1 == (n=write(1,mem+n, status.st_size+10000-n))) {
	perror("write");
	return 1;
}

printf("\nn=%d\n",n);
return 0;
}

#1 lore raw
Quoted 9 lines · Sébastien Paumier

Hi,
I have a question about mmap's behavior when one tries to map a file asking for a length greater than the actual file size. When I run the attached code on a 100 bytes file, I have the following output:

(... file content followed by zeros...)
n=4096
write: Bad address

Quoted 6 lines

So, it seems that the actual memory area provided by mmap is one page large and not the requested length of filesize+10000. I guess that 'write' writes less than requested because it was interrupted by the SIGBUS signal. And my question is:

shouldn't mmap either complain about the requested length or provide an accessible area of the requested length, instead of silently failing ?

Accessing non existing memory leads to SIGBUS signal, not a silent failure. Its documented behavior.

man mmap

SIGBUS Attempted access to a portion of the buffer that does not corre‐
spond to the file (for example, beyond the end of the file, including the case where another process has truncated the file).