Back to index

glibc  2.9
tst-mmap-offend.c
Go to the documentation of this file.
00001 /* Test case for bug with mmap stdio read past end of file.  */
00002 
00003 #include <stdio.h>
00004 #include <error.h>
00005 #include <errno.h>
00006 
00007 static void do_prepare (void);
00008 #define PREPARE(argc, argv) do_prepare ()
00009 static int do_test (void);
00010 #define TEST_FUNCTION do_test ()
00011 #include <test-skeleton.c>
00012 
00013 static char *temp_file;
00014 
00015 static const char text1[] = "hello\n";
00016 
00017 static void
00018 do_prepare (void)
00019 {
00020   int temp_fd = create_temp_file ("tst-mmap-offend.", &temp_file);
00021   if (temp_fd == -1)
00022     error (1, errno, "cannot create temporary file");
00023   else
00024     {
00025       ssize_t cc = write (temp_fd, text1, sizeof text1 - 1);
00026       if (cc != sizeof text1 - 1)
00027        error (1, errno, "cannot write to temporary file");
00028     }
00029   close (temp_fd);
00030 }
00031 
00032 static int
00033 do_test (void)
00034 {
00035   unsigned char buffer[8192];
00036   int result = 0;
00037   FILE *f = fopen (temp_file, "rm");
00038   size_t cc;
00039 
00040   if (f == NULL)
00041     {
00042       perror (temp_file);
00043       return 1;
00044     }
00045 
00046   cc = fread (buffer, 1, sizeof (buffer), f);
00047   printf ("fread %zu: \"%.*s\"\n", cc, (int) cc, buffer);
00048   if (cc != sizeof text1 - 1)
00049     {
00050       perror ("fread");
00051       result = 1;
00052     }
00053 
00054   if (fseek (f, 2048, SEEK_SET) != 0)
00055     {
00056       perror ("fseek off end");
00057       result = 1;
00058     }
00059 
00060   if (fread (buffer, 1, sizeof (buffer), f) != 0
00061       || ferror (f) || !feof (f))
00062     {
00063       printf ("after fread error %d eof %d\n",
00064              ferror (f), feof (f));
00065       result = 1;
00066     }
00067 
00068   printf ("ftell %ld\n", ftell (f));
00069 
00070   if (fseek (f, 0, SEEK_SET) != 0)
00071     {
00072       perror ("fseek rewind");
00073       result = 1;
00074     }
00075 
00076   cc = fread (buffer, 1, sizeof (buffer), f);
00077   printf ("fread after rewind %zu: \"%.*s\"\n", cc, (int) cc, buffer);
00078   if (cc != sizeof text1 - 1)
00079     {
00080       perror ("fread after rewind");
00081       result = 1;
00082     }
00083 
00084   fclose (f);
00085   return result;
00086 }