mmap-file.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. static 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. /* need a barrier to assign message before SIGBUS due to a[4096] */
  66. asm volatile ("nop" ::: "memory");
  67. a[4096] = 0xff;
  68. if (signal(SIGBUS, SIG_DFL) == SIG_ERR) {
  69. perror("signal");
  70. return 1;
  71. }
  72. return 0;
  73. }