1
0

posix_mmap.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2017/11/30 Bernard The first version.
  9. */
  10. #include <stdint.h>
  11. #include <stdio.h>
  12. #include <rtthread.h>
  13. #include <dfs_posix.h>
  14. #include <sys/mman.h>
  15. void *mmap(void *addr, size_t length, int prot, int flags,
  16. int fd, off_t offset)
  17. {
  18. uint8_t *mem;
  19. if (addr)
  20. {
  21. mem = addr;
  22. }
  23. else mem = (uint8_t *)malloc(length);
  24. if (mem)
  25. {
  26. off_t cur;
  27. size_t read_bytes;
  28. cur = lseek(fd, 0, SEEK_SET);
  29. lseek(fd, offset, SEEK_SET);
  30. read_bytes = read(fd, mem, length);
  31. if (read_bytes != length)
  32. {
  33. if (addr == RT_NULL)
  34. {
  35. /* read failed */
  36. free(mem);
  37. mem = RT_NULL;
  38. }
  39. }
  40. lseek(fd, cur, SEEK_SET);
  41. return mem;
  42. }
  43. errno = ENOMEM;
  44. return MAP_FAILED;
  45. }
  46. int munmap(void *addr, size_t length)
  47. {
  48. if (addr)
  49. {
  50. free(addr);
  51. return 0;
  52. }
  53. return -1;
  54. }