xref: /nrf52832-nimble/rt-thread/components/libc/mmap/posix_mmap.c (revision 104654410c56c573564690304ae786df310c91fc)
1 /*
2  * Copyright (c) 2006-2018, 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 
11 #include <stdint.h>
12 #include <stdio.h>
13 
14 #include <rtthread.h>
15 #include <dfs_posix.h>
16 
17 #include <sys/mman.h>
18 
mmap(void * addr,size_t length,int prot,int flags,int fd,off_t offset)19 void *mmap(void *addr, size_t length, int prot, int flags,
20     int fd, off_t offset)
21 {
22     uint8_t *mem;
23 
24     if (addr)
25     {
26         mem = addr;
27     }
28     else mem = (uint8_t *)malloc(length);
29 
30     if (mem)
31     {
32         off_t cur;
33         size_t read_bytes;
34 
35         cur = lseek(fd, 0, SEEK_SET);
36 
37         lseek(fd, offset, SEEK_SET);
38         read_bytes = read(fd, mem, length);
39         if (read_bytes != length)
40         {
41             if (addr == RT_NULL)
42             {
43                 /* read failed */
44                 free(mem);
45                 mem = RT_NULL;
46             }
47         }
48         lseek(fd, cur, SEEK_SET);
49 
50         return mem;
51     }
52 
53     errno = ENOMEM;
54 
55     return MAP_FAILED;
56 }
57 
munmap(void * addr,size_t length)58 int munmap(void *addr, size_t length)
59 {
60     if (addr)
61     {
62         free(addr);
63         return 0;
64     }
65 
66     return -1;
67 }
68