]>
git.proxmox.com Git - wasi-libc.git/blob - libc-bottom-half/mman/mman.c
f02b136cd248582d5f3f628bcffa575b76151ee1
1 // Userspace emulation of mmap and munmap. Restrictions apply.
3 // This is meant to be complete enough to be compatible with code that uses
4 // mmap for simple file I/O. It just allocates memory with malloc and reads
5 // and writes data with pread and pwrite.
7 #define _WASI_EMULATED_MMAN
13 #include <sys/types.h>
22 void *mmap(void *addr
, size_t length
, int prot
, int flags
,
23 int fd
, off_t offset
) {
24 // Check for unsupported flags.
25 if ((flags
& (MAP_PRIVATE
| MAP_SHARED
)) == 0 ||
26 (flags
& MAP_FIXED
) != 0 ||
27 #ifdef MAP_SHARED_VALIDATE
28 (flags
& MAP_SHARED_VALIDATE
) == MAP_SHARED_VALIDATE
||
31 (flags
& MAP_NORESERVE
) != 0 ||
34 (flags
& MAP_GROWSDOWN
) != 0 ||
37 (flags
& MAP_HUGETLB
) != 0 ||
39 #ifdef MAP_FIXED_NOREPLACE
40 (flags
& MAP_FIXED_NOREPLACE
) != 0 ||
48 // Check for unsupported protection requests.
49 if (prot
== PROT_NONE
||
51 (prot
& PROT_EXEC
) != 0 ||
59 // To be consistent with POSIX.
65 // Check for integer overflow.
67 if (__builtin_add_overflow(length
, sizeof(struct map
), &buf_len
)) {
72 // Allocate the memory.
73 struct map
*map
= malloc(buf_len
);
79 // Initialize the header.
85 // Initialize the main memory buffer, either with the contents of a file,
88 if ((flags
& MAP_ANON
) == 0) {
89 char *body
= (char *)addr
;
91 const ssize_t nread
= pread(fd
, body
, length
, offset
);
99 length
-= (size_t)nread
;
100 offset
+= (size_t)nread
;
101 body
+= (size_t)nread
;
104 memset(addr
, 0, length
);
110 int munmap(void *addr
, size_t length
) {
111 struct map
*map
= (struct map
*)addr
- 1;
113 // We don't support partial munmapping.
114 if (map
->length
!= length
) {
119 // Release the memory.