tst-mmap-offend.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* Test case for bug with mmap stdio read past end of file. */
  2. #include <stdio.h>
  3. #include <error.h>
  4. #include <errno.h>
  5. static void do_prepare (void);
  6. #define PREPARE(argc, argv) do_prepare ()
  7. static int do_test (void);
  8. #define TEST_FUNCTION do_test ()
  9. #include <test-skeleton.c>
  10. static char *temp_file;
  11. static const char text1[] = "hello\n";
  12. static void
  13. do_prepare (void)
  14. {
  15. int temp_fd = create_temp_file ("tst-mmap-offend.", &temp_file);
  16. if (temp_fd == -1)
  17. error (1, errno, "cannot create temporary file");
  18. else
  19. {
  20. ssize_t cc = write (temp_fd, text1, sizeof text1 - 1);
  21. if (cc != sizeof text1 - 1)
  22. error (1, errno, "cannot write to temporary file");
  23. }
  24. close (temp_fd);
  25. }
  26. static int
  27. do_test (void)
  28. {
  29. unsigned char buffer[8192];
  30. int result = 0;
  31. FILE *f = fopen (temp_file, "rm");
  32. size_t cc;
  33. if (f == NULL)
  34. {
  35. perror (temp_file);
  36. return 1;
  37. }
  38. cc = fread (buffer, 1, sizeof (buffer), f);
  39. printf ("fread %zu: \"%.*s\"\n", cc, (int) cc, buffer);
  40. if (cc != sizeof text1 - 1)
  41. {
  42. perror ("fread");
  43. result = 1;
  44. }
  45. if (fseek (f, 2048, SEEK_SET) != 0)
  46. {
  47. perror ("fseek off end");
  48. result = 1;
  49. }
  50. if (fread (buffer, 1, sizeof (buffer), f) != 0
  51. || ferror (f) || !feof (f))
  52. {
  53. printf ("after fread error %d eof %d\n",
  54. ferror (f), feof (f));
  55. result = 1;
  56. }
  57. printf ("ftell %ld\n", ftell (f));
  58. if (fseek (f, 0, SEEK_SET) != 0)
  59. {
  60. perror ("fseek rewind");
  61. result = 1;
  62. }
  63. cc = fread (buffer, 1, sizeof (buffer), f);
  64. printf ("fread after rewind %zu: \"%.*s\"\n", cc, (int) cc, buffer);
  65. if (cc != sizeof text1 - 1)
  66. {
  67. perror ("fread after rewind");
  68. result = 1;
  69. }
  70. fclose (f);
  71. return result;
  72. }