posix_mmap.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * File : posix_mmap.c
  3. * This file is part of RT-Thread RTOS
  4. * COPYRIGHT (C) 2017, RT-Thread Development Team
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. *
  20. * Change Logs:
  21. * Date Author Notes
  22. * 2017/11/30 Bernard The first version.
  23. */
  24. #include <stdint.h>
  25. #include <stdio.h>
  26. #include <rtthread.h>
  27. #include <dfs_posix.h>
  28. #include <sys/mman.h>
  29. void *mmap(void *addr, size_t length, int prot, int flags,
  30. int fd, off_t offset)
  31. {
  32. uint8_t *mem;
  33. if (addr)
  34. {
  35. mem = addr;
  36. }
  37. else mem = (uint8_t *)malloc(length);
  38. if (mem)
  39. {
  40. off_t cur;
  41. size_t read_bytes;
  42. cur = lseek(fd, 0, SEEK_SET);
  43. lseek(fd, offset, SEEK_SET);
  44. read_bytes = read(fd, addr, length);
  45. if (read_bytes != length)
  46. {
  47. if (addr == RT_NULL)
  48. {
  49. /* read failed */
  50. free(mem);
  51. mem = RT_NULL;
  52. }
  53. }
  54. lseek(fd, cur, SEEK_SET);
  55. return mem;
  56. }
  57. errno = ENOMEM;
  58. return MAP_FAILED;
  59. }
  60. int munmap(void *addr, size_t length)
  61. {
  62. if (addr)
  63. {
  64. free(addr);
  65. return 0;
  66. }
  67. return -1;
  68. }