1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "ecmascript/platform/map.h"
17
18 #include <cerrno>
19 #include <sys/mman.h>
20 #include <unistd.h>
21
22 #include "ecmascript/log_wrapper.h"
23 #include "ecmascript/mem/mem.h"
24 #include "ecmascript/platform/os.h"
25
26 namespace panda::ecmascript {
PageMap(size_t size,int prot,size_t alignment)27 MemMap PageMap(size_t size, int prot, size_t alignment)
28 {
29 ASSERT(size == AlignUp(size, PageSize()));
30 ASSERT(alignment == AlignUp(alignment, PageSize()));
31 size_t allocSize = size + alignment;
32 void *result = mmap(nullptr, allocSize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
33 if (reinterpret_cast<intptr_t>(result) == -1) {
34 LOG_ECMA(FATAL) << "mmap failed with error code:" << errno;
35 }
36 if (alignment != 0) {
37 auto alignResult = AlignUp(reinterpret_cast<uintptr_t>(result), alignment);
38 size_t leftSize = alignResult - reinterpret_cast<uintptr_t>(result);
39 size_t rightSize = alignment - leftSize;
40 void *alignEndResult = reinterpret_cast<void *>(alignResult + size);
41 munmap(result, leftSize);
42 munmap(alignEndResult, rightSize);
43 result = reinterpret_cast<void *>(alignResult);
44 }
45 return MemMap(result, size);
46 }
47
PageUnmap(MemMap it)48 void PageUnmap(MemMap it)
49 {
50 munmap(it.GetMem(), it.GetSize());
51 }
52
MachineCodePageMap(size_t size,int prot,size_t alignment)53 MemMap MachineCodePageMap(size_t size, int prot, size_t alignment)
54 {
55 MemMap memMap = PageMap(size, prot, alignment);
56 PageTag(memMap.GetMem(), memMap.GetSize());
57 return memMap;
58 }
59
MachineCodePageUnmap(MemMap it)60 void MachineCodePageUnmap(MemMap it)
61 {
62 PageTag(it.GetMem(), it.GetSize(), true);
63 PageUnmap(it);
64 }
65
PageRelease(void * mem,size_t size)66 void PageRelease(void *mem, size_t size)
67 {
68 madvise(mem, size, MADV_DONTNEED);
69 }
70
PageTag(void * mem,size_t size,bool remove)71 void PageTag(void *mem, size_t size, bool remove)
72 {
73 if (remove) {
74 PrctlSetVMA(mem, size, nullptr);
75 } else {
76 PrctlSetVMA(mem, size, "ArkJS Heap");
77 }
78 }
79
PageProtect(void * mem,size_t size,int prot)80 void PageProtect(void *mem, size_t size, int prot)
81 {
82 mprotect(mem, size, prot);
83 }
84
PageSize()85 size_t PageSize()
86 {
87 return getpagesize();
88 }
89 } // namespace panda::ecmascript
90