mman.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 <unistd.h>
  14. #include <sys/stat.h>
  15. #include <sys/statfs.h>
  16. #include <sys/errno.h>
  17. #include "sys/mman.h"
  18. void *mmap(void *addr, size_t length, int prot, int flags,
  19. int fd, off_t offset)
  20. {
  21. uint8_t *mem;
  22. if (addr)
  23. {
  24. mem = addr;
  25. }
  26. else mem = (uint8_t *)malloc(length);
  27. if (mem)
  28. {
  29. off_t cur;
  30. size_t read_bytes;
  31. cur = lseek(fd, 0, SEEK_SET);
  32. lseek(fd, offset, SEEK_SET);
  33. read_bytes = read(fd, mem, length);
  34. if (read_bytes != length)
  35. {
  36. if (addr == RT_NULL)
  37. {
  38. /* read failed */
  39. free(mem);
  40. mem = RT_NULL;
  41. }
  42. }
  43. lseek(fd, cur, SEEK_SET);
  44. return mem;
  45. }
  46. errno = ENOMEM;
  47. return MAP_FAILED;
  48. }
  49. int munmap(void *addr, size_t length)
  50. {
  51. if (addr)
  52. {
  53. free(addr);
  54. return 0;
  55. }
  56. return -1;
  57. }