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