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 #ifndef RUNTIME_ECMASCRIPT_CHUNK_H 17 #define RUNTIME_ECMASCRIPT_CHUNK_H 18 19 #include "ecmascript/mem/ecma_list.h" 20 #include "ecmascript/mem/area.h" 21 22 namespace panda::ecmascript { 23 class NativeAreaAllocator; 24 25 class Chunk { 26 public: 27 static constexpr size_t MEM_ALIGN = 8U; 28 29 explicit Chunk(NativeAreaAllocator *allocator); ~Chunk()30 ~Chunk() 31 { 32 ReleaseMemory(); 33 } 34 35 NO_COPY_SEMANTIC(Chunk); 36 NO_MOVE_SEMANTIC(Chunk); 37 Allocate(size_t size)38 [[nodiscard]] void *Allocate(size_t size) 39 { 40 if (size == 0) { 41 LOG_ECMA_MEM(FATAL) << "size must have a size bigger than 0"; 42 UNREACHABLE(); 43 } 44 uintptr_t result = ptr_; 45 size = AlignUp(size, MEM_ALIGN); 46 if (UNLIKELY(size > end_ - ptr_)) { 47 result = Expand(size); 48 } else { 49 ptr_ += size; 50 } 51 52 return reinterpret_cast<void *>(result); 53 } 54 55 template<class T> NewArray(size_t size)56 [[nodiscard]] T *NewArray(size_t size) 57 { 58 return static_cast<T *>(Allocate(size * sizeof(T))); 59 } 60 61 template<typename T, typename... Args> New(Args &&...args)62 [[nodiscard]] T *New(Args &&... args) 63 { 64 auto p = reinterpret_cast<void *>(Allocate(sizeof(T))); 65 new (p) T(std::forward<Args>(args)...); 66 return reinterpret_cast<T *>(p); 67 } 68 69 template<class T> Delete(T * ptr)70 void Delete(T *ptr) 71 { 72 ASSERT(ptr != nullptr); 73 // NOLINTNEXTLINE(readability-braces-around-statements,bugprone-suspicious-semicolon) 74 if constexpr (std::is_class_v<T>) { 75 ptr->~T(); 76 } 77 Free(ptr); 78 } 79 Free(void * mem)80 void Free([[maybe_unused]] void *mem) 81 { 82 // do nothing 83 } 84 85 private: 86 uintptr_t Expand(size_t size); 87 Area *NewArea(size_t size); 88 void ReleaseMemory(); 89 90 uintptr_t ptr_{0}; 91 uintptr_t end_{0}; 92 93 Area *currentArea_{nullptr}; 94 EcmaList<Area> areaList_{}; 95 NativeAreaAllocator *allocator_{nullptr}; 96 }; 97 } // namespace panda::ecmascript 98 99 #endif // RUNTIME_ECMASCRIPT_CHUNK_H 100