mman.c 1.2 KB

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