fileio.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (C) 2025 Midokura Japan KK. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. /*
  6. * modified copy-and-paste from:
  7. * https://github.com/yamt/toywasm/blob/0eaad8cacd0cc7692946ff19b25994f106113be8/lib/fileio.c
  8. */
  9. #include <sys/stat.h>
  10. #include <assert.h>
  11. #include <errno.h>
  12. #include <fcntl.h>
  13. #include <stdlib.h>
  14. #include <unistd.h>
  15. #include "fileio.h"
  16. int
  17. map_file(const char *path, void **pp, size_t *sizep)
  18. {
  19. void *p;
  20. size_t size;
  21. ssize_t ssz;
  22. int fd;
  23. int ret;
  24. fd = open(path, O_RDONLY);
  25. if (fd == -1) {
  26. ret = errno;
  27. assert(ret != 0);
  28. return ret;
  29. }
  30. struct stat st;
  31. ret = fstat(fd, &st);
  32. if (ret == -1) {
  33. ret = errno;
  34. assert(ret != 0);
  35. close(fd);
  36. return ret;
  37. }
  38. size = st.st_size;
  39. if (size > 0) {
  40. p = malloc(size);
  41. }
  42. else {
  43. /* Avoid a confusing error */
  44. p = malloc(1);
  45. }
  46. if (p == NULL) {
  47. close(fd);
  48. return ENOMEM;
  49. }
  50. ssz = read(fd, p, size);
  51. if (ssz != size) {
  52. ret = errno;
  53. assert(ret != 0);
  54. close(fd);
  55. return ret;
  56. }
  57. close(fd);
  58. *pp = p;
  59. *sizep = size;
  60. return 0;
  61. }
  62. void
  63. unmap_file(void *p, size_t sz)
  64. {
  65. free(p);
  66. }