get_fs.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /******************************************************************************
  2. * MiniFFS : Mini Flat File System
  3. * This file is part of the test suite of MiniFFS
  4. *
  5. * This file abstract the filesystem opening, to be able to test both FILE and
  6. * MEMORY backend.
  7. *
  8. * Copyright (c) 2008-2022 986-Studio. All rights reserved.
  9. *
  10. ******************************************************************************/
  11. #ifndef _WIN32
  12. #include <sys/mman.h>
  13. #include <sys/types.h>
  14. #include <unistd.h>
  15. #include <fcntl.h>
  16. #endif
  17. static miniffs_t *get_fs(const char *filename)
  18. {
  19. #ifdef BUILD_PLATFORM_MEMORY
  20. char *fs_image;
  21. size_t fileSize;
  22. #ifdef _WIN32
  23. /* As windows do not provide an easy to use mmap equivalent, let's use the fallback
  24. * of opening the file, allocating memory and read the file in the said memory
  25. */
  26. FILE *fp;
  27. fp = fopen(filename, "rb");
  28. fseek(fp, 0, SEEK_END);
  29. fileSize = ftell(fp);
  30. fseek(fp, 0, SEEK_SET);
  31. fs_image = (char *)calloc(1, fileSize);
  32. fread(fs_image, 1, fileSize, fp);
  33. fclose(fp);
  34. #else
  35. int fd;
  36. struct stat FileStat;
  37. fd = open(filename, O_RDWR);
  38. fstat(fd, &FileStat);
  39. fs_image = (char *)mmap(NULL, FileStat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  40. close(fd);
  41. fileSize = FileStat.st_size;
  42. if (fs_image == MAP_FAILED)
  43. {
  44. fs_image = NULL;
  45. }
  46. #endif
  47. return miniffs_openfs((uintptr_t)fs_image);
  48. #else
  49. return miniffs_openfs(filename);
  50. #endif
  51. }