• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 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 ECMASCRIPT_WORK_SPACE_CHUNK_H
17 #define ECMASCRIPT_WORK_SPACE_CHUNK_H
18 
19 #include "ecmascript/common.h"
20 #include "ecmascript/log_wrapper.h"
21 #include "ecmascript/mem/ecma_list.h"
22 #include "ecmascript/mem/area.h"
23 #include "ecmascript/mem/chunk.h"
24 #include "ecmascript/mem/c_containers.h"
25 #include "ecmascript/platform/mutex.h"
26 
27 namespace panda::ecmascript {
28 class NativeAreaAllocator;
29 
30 class PUBLIC_API WorkSpaceChunk {
31 public:
32     static constexpr size_t MEM_ALIGN = 8U;
33 
34     explicit WorkSpaceChunk(NativeAreaAllocator *allocator);
35     WorkSpaceChunk() = default;
~WorkSpaceChunk()36     ~WorkSpaceChunk()
37     {
38         ReleaseMemory();
39     }
40 
41     NO_COPY_SEMANTIC(WorkSpaceChunk);
42     NO_MOVE_SEMANTIC(WorkSpaceChunk);
43 
Allocate(size_t size)44     void *Allocate(size_t size)
45     {
46         LockHolder lock(mtx_);
47         if (size != WORKNODE_SPACE_SIZE) {
48             LOG_ECMA_MEM(FATAL) << "WorkNode size is illegal, size:" << size;
49             UNREACHABLE();
50         }
51         uintptr_t result = 0;
52         if (!cachedAreaList_.empty()) {
53             result = cachedAreaList_.back();
54             cachedAreaList_.pop_back();
55             return reinterpret_cast<void *>(result);
56         }
57         size = AlignUp(size, MEM_ALIGN);
58         result = NewArea(size);
59 
60         return reinterpret_cast<void *>(result);
61     }
62 
63     void Free([[maybe_unused]] void *mem);
64 
65 private:
66     uintptr_t NewArea(size_t size);
67     void ReleaseMemory();
68     static constexpr size_t MAX_WORK_SPACE_CHUNK_SIZE = 2_MB;
69     NativeAreaAllocator *allocator_ {nullptr};
70     Mutex mtx_;
71     CUnorderedMap<uintptr_t, uintptr_t> areaList_ {};
72     CList<uintptr_t> cachedAreaList_ {};
73 };
74 }  // namespace panda::ecmascript
75 #endif  // ECMASCRIPT_WORK_SPACE_CHUNK_H
76