#include #include #include #include #include int main(void) { int flag; int npgalloc = 33, npggood = 32, npgbad = npgalloc - npggood; int pagesize = getpagesize(); void *p = NULL; ssize_t nwrit; /* Clear O_APPEND. */ if ((flag = fcntl(STDOUT_FILENO, F_GETFL)) == -1) err(1, "fcntl(F_GETFL)"); flag &= ~O_APPEND; if (fcntl(STDOUT_FILENO, F_SETFL, flag) == -1) err(1, "fcntl(F_SETFL)"); /* Allocate a batch of pages. */ if ((p = mmap(NULL, npgalloc*pagesize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) err(1, "mmap"); /* Write zeros. */ if (lseek(STDOUT_FILENO, 0, SEEK_SET) == -1) warn("lseek"); if ((nwrit = write(STDOUT_FILENO, p, npgalloc*pagesize)) == -1) err(1, "write"); warnx("nwrit=%zd", nwrit); /* Replace by nonzero. */ memset(p, 0xc5, npgalloc*pagesize); /* Render the last chunk of pages unwritable. */ #if 1 if (mprotect(p + npggood*pagesize, npgbad*pagesize, PROT_NONE) == -1) err(1, "mprotect"); #elif 0 if (mprotect(p + npggood*pagesize, npgbad*pagesize, PROT_WRITE) == -1) err(1, "mprotect"); #else if (munmap(p + npggood*pagesize, npgbad*pagesize) == -1) err(1, "munmap"); #endif /* Write it out. */ if (lseek(STDOUT_FILENO, 0, SEEK_SET) == -1) warn("lseek"); if ((nwrit = write(STDOUT_FILENO, p, npgalloc*pagesize)) == -1) err(1, "write"); warnx("nwrit=%zd", nwrit); return 0; }