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/chunk.h" 17 18 #include "ecmascript/mem/heap.h" 19 20 namespace panda::ecmascript { Chunk(NativeAreaAllocator * allocator)21Chunk::Chunk(NativeAreaAllocator *allocator) : allocator_(allocator) {} 22 NewArea(size_t size)23Area *Chunk::NewArea(size_t size) 24 { 25 auto area = allocator_->AllocateArea(size); 26 if (area == nullptr) { 27 LOG_ECMA_MEM(FATAL) << "OOM Chunk : NewArea area is nullptr"; 28 UNREACHABLE(); 29 } 30 allocator_->IncreaseNativeSizeStats(size, NativeFlag::CHUNK_MEM); 31 areaList_.AddNode(area); 32 currentArea_ = area; 33 return area; 34 } 35 Expand(size_t size)36uintptr_t Chunk::Expand(size_t size) 37 { 38 ASSERT(end_ - ptr_ < size); 39 40 Area *head = currentArea_; 41 size_t newSize; 42 if (head != nullptr) { 43 // NOLINTNEXTLINE(hicpp-signed-bitwise) 44 newSize = size + (head->GetSize() << 1); 45 } else { 46 newSize = sizeof(Area) + MEM_ALIGN + size; 47 } 48 49 if (newSize < MIN_CHUNK_AREA_SIZE) { 50 newSize = MIN_CHUNK_AREA_SIZE; 51 } else if (newSize > MAX_CHUNK_AREA_SIZE) { 52 size_t minNewSize = sizeof(Area) + MEM_ALIGN + size; 53 newSize = std::max(minNewSize, MAX_CHUNK_AREA_SIZE); 54 } 55 56 if (newSize > static_cast<size_t>(std::numeric_limits<int>::max())) { 57 LOG_ECMA_MEM(FATAL) << "OOM chunk : newSize is "<< newSize << ", size is " << size; 58 UNREACHABLE(); 59 } 60 61 Area *area = NewArea(newSize); 62 if (area == nullptr) { 63 LOG_ECMA_MEM(FATAL) << "OOM chunk : NewArea area is nullptr"; 64 UNREACHABLE(); 65 } 66 uintptr_t result = AlignUp(area->GetBegin(), MEM_ALIGN); 67 ptr_ = result + size; 68 end_ = area->GetEnd(); 69 return result; 70 } 71 ReleaseMemory()72void Chunk::ReleaseMemory() 73 { 74 while (!areaList_.IsEmpty()) { 75 Area *node = areaList_.PopBack(); 76 allocator_->FreeArea(node); 77 } 78 ptr_ = 0; 79 end_ = 0; 80 } 81 } // namespace panda::ecmascript 82