1 /*
2 * Copyright (c) 2021 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/mem/heap_region_allocator.h"
17 #include "ecmascript/mem/heap.h"
18 #include "ecmascript/mem/mark_stack.h"
19 #include "ecmascript/mem/region.h"
20 #include "libpandabase/mem/pool_manager.h"
21
22 namespace panda::ecmascript {
AllocateAlignedRegion(Space * space,size_t capacity)23 Region *HeapRegionAllocator::AllocateAlignedRegion(Space *space, size_t capacity)
24 {
25 if (capacity == 0) {
26 LOG_ECMA_MEM(FATAL) << "capacity must have a size bigger than 0";
27 UNREACHABLE();
28 }
29 auto pool = PoolManager::GetMmapMemPool()->AllocPool(capacity, panda::SpaceType::SPACE_TYPE_OBJECT,
30 AllocatorType::RUNSLOTS_ALLOCATOR, nullptr);
31 void *mapMem = pool.GetMem();
32 if (mapMem == nullptr) {
33 LOG_ECMA_MEM(FATAL) << "pool is empty " << annoMemoryUsage_.load(std::memory_order_relaxed);
34 UNREACHABLE();
35 }
36 #if ECMASCRIPT_ENABLE_ZAP_MEM
37 if (memset_s(mapMem, capacity, 0, capacity) != EOK) {
38 LOG_ECMA(FATAL) << "memset_s failed";
39 UNREACHABLE();
40 }
41 #endif
42 IncreaseAnnoMemoryUsage(capacity);
43
44 uintptr_t mem = ToUintPtr(mapMem);
45 // Check that the address is 256K byte aligned
46 LOG_IF(AlignUp(mem, PANDA_POOL_ALIGNMENT_IN_BYTES) != mem, FATAL, RUNTIME) << "region not align by 256KB";
47
48 // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
49 uintptr_t begin = AlignUp(mem + sizeof(Region), static_cast<size_t>(MemAlignment::MEM_ALIGN_REGION));
50 uintptr_t end = mem + capacity;
51
52 return new (ToVoidPtr(mem)) Region(space, space->GetHeap(), mem, begin, end,
53 space->GetHeap()->GetNativeAreaAllocator());
54 }
55
FreeRegion(Region * region)56 void HeapRegionAllocator::FreeRegion(Region *region)
57 {
58 auto size = region->GetCapacity();
59 DecreaseAnnoMemoryUsage(size);
60 #if ECMASCRIPT_ENABLE_ZAP_MEM
61 if (memset_s(ToVoidPtr(region->GetAllocateBase()), size, INVALID_VALUE, size) != EOK) {
62 LOG_ECMA(FATAL) << "memset_s failed";
63 UNREACHABLE();
64 }
65 #endif
66 PoolManager::GetMmapMemPool()->FreePool(ToVoidPtr(region->GetAllocateBase()), size);
67 }
68 } // namespace panda::ecmascript
69