Search code examples
linuxmemory-mapped-filesecryptfs

Memory mapped files failing in ecryptfs directory


On a regular ubuntu machine, the following test succeeds unless I run it in my home directory, in which case it crashes with a bus error. All I can think of is that it's because the home directory is encrypted. (I find Private and .ecryptfs links there.)

// Make with g++ -mcmodel=large -fPIC -g -O0 -o checkmm checkmm.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>

#define TALLIES "tallies.bin"
#define NUM_TALLIES (550588000/sizeof(int))
typedef struct { int tallies[NUM_TALLIES]; } World;
World* world;

void loadWorld() {
  int fd = open(TALLIES, O_RDWR | O_CREAT);
  if (fd == -1) { printf("Can't open tallies file %s\n", TALLIES); exit(0); }
  fallocate(fd, 0, 0, sizeof(World));
  world = (World*) mmap(0, sizeof(World), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  if (world ==(World*) -1) { printf("Failed to map tallies file %s\n", TALLIES); exit(1); }
}

void unloadWorld() { munmap(world, sizeof(World)); }

void resetWorld() {
  int i;
  for (i=0;i<NUM_TALLIES;i++) world->tallies[i]=-1;
}

int main() {
  loadWorld();
  resetWorld();
  unloadWorld();
}

Can anyone elucidate?


Solution

  • You should check the return codes for each system call. Particularly fallocate() and mmap().

    fallocate() is supported on a handful of filesystems. You should use ftruncate() if fallocate() fails (with errno set to EOPNOTSUPP).