1 /*
2 * Copyright 2012, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <unistd.h>
18 #include <errno.h>
19 #include <sys/mman.h>
20 #include <mman_portable.h>
21
22 #if MAP_ANONYMOUS_PORTABLE==MAP_ANONYMOUS
23 #error Bad build environment
24 #endif
25
mips_change_prot(int prot)26 static inline int mips_change_prot(int prot)
27 {
28 /* Only PROT_SEM is different */
29 if (prot & PROT_SEM_PORTABLE) {
30 prot &= ~PROT_SEM_PORTABLE;
31 prot |= PROT_SEM;
32 }
33
34 return prot;
35 }
36
mips_change_flags(int flags)37 static inline int mips_change_flags(int flags)
38 {
39 int mipsflags = 0;
40 if (flags & MAP_SHARED_PORTABLE)
41 mipsflags |= MAP_SHARED;
42 if (flags & MAP_PRIVATE_PORTABLE)
43 mipsflags |= MAP_PRIVATE;
44 if (flags & MAP_FIXED_PORTABLE)
45 mipsflags |= MAP_FIXED;
46 if (flags & MAP_ANONYMOUS_PORTABLE)
47 mipsflags |= MAP_ANONYMOUS;
48 if (flags & MAP_GROWSDOWN_PORTABLE)
49 mipsflags |= MAP_GROWSDOWN;
50 if (flags & MAP_DENYWRITE_PORTABLE)
51 mipsflags |= MAP_DENYWRITE;
52 if (flags & MAP_EXECUTABLE_PORTABLE)
53 mipsflags |= MAP_EXECUTABLE;
54 if (flags & MAP_LOCKED_PORTABLE)
55 mipsflags |= MAP_LOCKED;
56 if (flags & MAP_NORESERVE_PORTABLE)
57 mipsflags |= MAP_NORESERVE;
58 if (flags & MAP_POPULATE_PORTABLE)
59 mipsflags |= MAP_POPULATE;
60 if (flags & MAP_NONBLOCK_PORTABLE)
61 mipsflags |= MAP_NONBLOCK;
62
63 return mipsflags;
64 }
65
66 #define MMAP2_SHIFT 12
67 extern void *__mmap2(void *, size_t, int, int, int, size_t);
mmap_portable(void * addr,size_t size,int prot,int flags,int fd,long offset)68 void *mmap_portable(void *addr, size_t size, int prot, int flags, int fd, long offset)
69 {
70 void *ret;
71 int mips_prot, mips_flags;
72
73 if (offset & ((1UL << MMAP2_SHIFT)-1)) {
74 errno = EINVAL;
75 return MAP_FAILED;
76 }
77
78 mips_prot = mips_change_prot(prot);
79 mips_flags = mips_change_flags(flags);
80 ret = __mmap2(addr, size, mips_prot, mips_flags, fd,
81 (size_t)offset >> MMAP2_SHIFT);
82
83 if (ret && (mips_flags & (MAP_PRIVATE | MAP_ANONYMOUS)))
84 madvise(ret, size, MADV_MERGEABLE);
85
86 return ret;
87 }
88
89 extern int mprotect(const void *, size_t, int);
mprotect_portable(const void * addr,size_t size,int prot)90 int mprotect_portable(const void *addr, size_t size, int prot)
91 {
92 return mprotect(addr, size, mips_change_prot(prot));
93 }
94