mprotect_file_fork.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #define _XOPEN_SOURCE 700
  2. #include <err.h>
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <stdio.h>
  6. #include <sys/mman.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <sys/wait.h>
  10. #include <unistd.h>
  11. #define FNAME "/tmp/test"
  12. #define VAL 0xff
  13. int main(void) {
  14. int fd;
  15. void *ptr;
  16. if (mkdir("/tmp", S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) {
  17. err(1, "mkdir");
  18. }
  19. if (unlink(FNAME) < 0 && errno != ENOENT) {
  20. err(1, "unlink");
  21. }
  22. fd = open(FNAME, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
  23. if (fd < 0) {
  24. err(1, "open");
  25. }
  26. if (ftruncate(fd, 0x10) < 0) {
  27. err(1, "ftruncate");
  28. }
  29. ptr = mmap(NULL, 0x1000, PROT_READ, MAP_PRIVATE, fd, 0);
  30. if (ptr == MAP_FAILED) {
  31. err(1, "mmap");
  32. }
  33. if (close(fd) < 0) {
  34. err(1, "close");
  35. }
  36. if (mprotect(ptr, 0x1000, PROT_READ | PROT_WRITE) < 0) {
  37. err(1, "mprotect");
  38. }
  39. *(int*)ptr = VAL;
  40. pid_t p = fork();
  41. if (p < 0) {
  42. err(1, "fork");
  43. }
  44. if (p == 0) {
  45. // child
  46. if (*(int*)ptr != VAL) {
  47. printf("EXPECTED: 0x%x\nGOT : 0x%x\n", VAL, *(int*)ptr);
  48. return 1;
  49. }
  50. return 0;
  51. }
  52. // parent
  53. int st = 0;
  54. if (wait(&st) < 0) {
  55. err(1, "wait");
  56. }
  57. if (unlink(FNAME) < 0) {
  58. err(1, "unlink");
  59. }
  60. if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) {
  61. printf("abnormal child termination: %d\n", st);
  62. return 1;
  63. }
  64. puts("Test successful!");
  65. return 0;
  66. }