mman.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * 2024/03/29 TroyMitchelle Add all function comments
  10. */
  11. #include <stdint.h>
  12. #include <stdio.h>
  13. #include <rtthread.h>
  14. #include <unistd.h>
  15. #include <stdlib.h>
  16. #include <sys/stat.h>
  17. #include <sys/statfs.h>
  18. #include <sys/errno.h>
  19. #include "sys/mman.h"
  20. /**
  21. * @brief Maps a region of memory into the calling process's address space.
  22. * @param addr Desired starting address of the mapping.
  23. * @param length Length of the mapping.
  24. * @param prot Protection of the mapped memory region.
  25. * @param flags Type of the mapped memory region.
  26. * @param fd File descriptor of the file to be mapped.
  27. * @param offset Offset within the file to start the mapping.
  28. * @return Upon success, returns a pointer to the mapped region; otherwise, MAP_FAILED is returned.
  29. */
  30. void *mmap(void *addr, size_t length, int prot, int flags,
  31. int fd, off_t offset)
  32. {
  33. uint8_t *mem;
  34. if (addr)
  35. {
  36. mem = addr;
  37. }
  38. else mem = (uint8_t *)malloc(length);
  39. if (mem)
  40. {
  41. off_t cur;
  42. size_t read_bytes;
  43. cur = lseek(fd, 0, SEEK_SET);
  44. lseek(fd, offset, SEEK_SET);
  45. read_bytes = read(fd, mem, length);
  46. if (read_bytes != length)
  47. {
  48. if (addr == RT_NULL)
  49. {
  50. /* read failed */
  51. free(mem);
  52. mem = RT_NULL;
  53. }
  54. }
  55. lseek(fd, cur, SEEK_SET);
  56. return mem;
  57. }
  58. errno = ENOMEM;
  59. return MAP_FAILED;
  60. }
  61. /**
  62. * @brief Unmaps a mapped region of memory.
  63. * @param addr Starting address of the mapping to be unmapped.
  64. * @param length Length of the mapping.
  65. * @return Upon success, returns 0; otherwise, -1 is returned.
  66. */
  67. int munmap(void *addr, size_t length)
  68. {
  69. if (addr)
  70. {
  71. free(addr);
  72. return 0;
  73. }
  74. return -1;
  75. }