mman.c 1.2 KB

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