mmap-file.c 1.9 KB

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