mmap-file.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <signal.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/mman.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include <unistd.h>
  8. const char* message;
  9. void SIGBUS_handler(int sig) {
  10. puts(message);
  11. exit(0);
  12. }
  13. int main(int argc, const char** argv) {
  14. int rv;
  15. /* Initalization: create a 1025-byte file */
  16. FILE* fp = fopen("testfile", "w+");
  17. if (!fp) {
  18. perror("fopen");
  19. return 1;
  20. }
  21. rv = ftruncate(fileno(fp), 1024);
  22. if (rv) {
  23. perror("ftruncate");
  24. return 1;
  25. }
  26. volatile unsigned char* a =
  27. mmap(NULL, 9162, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FILE, fileno(fp), 0);
  28. if (a == MAP_FAILED) {
  29. perror("mmap");
  30. return 1;
  31. }
  32. a[1023] = 0xff;
  33. a[4095] = 0xff;
  34. asm volatile ("nop" ::: "memory");
  35. int pid = fork();
  36. if (pid == -1) {
  37. perror("fork");
  38. return 1;
  39. }
  40. if (pid != 0) {
  41. rv = waitpid(pid, NULL, 0);
  42. if (rv == -1) {
  43. perror("waitpid");
  44. return 1;
  45. }
  46. }
  47. asm volatile ("nop" ::: "memory");
  48. a[0] = 0xff;
  49. printf(pid == 0 ? "mmap test 1 passed\n" : "mmap test 6 passed\n");
  50. a[1024] = 0xff;
  51. printf(pid == 0 ? "mmap test 2 passed\n" : "mmap test 7 passed\n");
  52. asm volatile ("nop" ::: "memory");
  53. if (pid == 0) {
  54. if (a[1023] == 0xff)
  55. printf("mmap test 3 passed\n");
  56. if (a[4095] == 0xff)
  57. printf("mmap test 4 passed\n");
  58. }
  59. asm volatile ("nop" ::: "memory");
  60. if (signal(SIGBUS, SIGBUS_handler) == SIG_ERR) {
  61. perror("signal");
  62. return 1;
  63. }
  64. message = pid == 0 ? "mmap test 5 passed\n" : "mmap test 8 passed\n";
  65. a[4096] = 0xff;
  66. if (signal(SIGBUS, SIG_DFL) == SIG_ERR) {
  67. perror("signal");
  68. return 1;
  69. }
  70. return 0;
  71. }