boot2

Playing with the boostrap
git clone https://git.ryansepassi.com/git/boot2.git
Log | Files | Refs | README

011-fseek.c (1481B)


      1 /* fseek -> stdio/fseek.c -> lseek (posix) -> _lseek -> sys_lseek.
      2  *
      3  * Lays a known payload in a tmp file, opens it for reading, fseek's
      4  * past the first 7 bytes, then fread's the next 5. Expected stdout is
      5  * "world" — the substring after "hello, ". Anchors the lseek path with
      6  * a non-zero, non-end offset so a SEEK_SET that silently no-ops would
      7  * read "hello," instead of "world". */
      8 typedef long FILE;
      9 typedef long ssize_t;
     10 typedef unsigned long size_t;
     11 
     12 extern FILE   *fopen  (char const *path, char const *mode);
     13 extern int     fclose (FILE *stream);
     14 extern int     fputs  (char const *s, FILE *stream);
     15 extern int     fseek  (FILE *stream, long offset, int whence);
     16 extern size_t  fread  (void *ptr, size_t size, size_t count, FILE *stream);
     17 extern ssize_t write  (int fd, void const *buf, size_t n);
     18 
     19 int
     20 main (void)
     21 {
     22   char const *path = "/tmp/boot2-cclibc-11";
     23 
     24   FILE *w = fopen (path, "w");
     25   if (!w)
     26     {
     27       write (1, "fopen-w-fail\n", 13);
     28       return 1;
     29     }
     30   fputs ("hello, world\n", w);
     31   fclose (w);
     32 
     33   FILE *r = fopen (path, "r");
     34   if (!r)
     35     {
     36       write (1, "fopen-r-fail\n", 13);
     37       return 2;
     38     }
     39   if (fseek (r, 7, 0))                  /* SEEK_SET = 0 */
     40     {
     41       write (1, "fseek-fail\n", 11);
     42       fclose (r);
     43       return 3;
     44     }
     45   char buf[8];
     46   size_t n = fread (buf, 1, 5, r);
     47   fclose (r);
     48 
     49   if (n != 5)
     50     {
     51       write (1, "short-read\n", 11);
     52       return 4;
     53     }
     54   buf[5] = '\n';
     55   write (1, buf, 6);
     56   return 0;
     57 }