1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "berberis/runtime_primitives/code_pool.h"
18 
19 #include <cstring>
20 #include <mutex>
21 
22 #include "berberis/base/forever_alloc.h"
23 #include "berberis/runtime_primitives/exec_region_anonymous.h"
24 
25 #if defined(__BIONIC__)
26 #include "berberis/runtime_primitives/exec_region_elf_backed.h"
27 #endif
28 
29 namespace berberis {
30 
AddRaw(const void * ptr,uint32_t size)31 void* DataPool::AddRaw(const void* ptr, uint32_t size) {
32   void* result;
33   // Take the lock to allocate in arena.
34   {
35     std::lock_guard<std::mutex> lock(mutex_);
36     result = arena_.Alloc(size, /* align = */ 16);
37   }
38   memcpy(result, ptr, size);
39   return result;
40 }
41 
ResetAllExecRegions()42 void ResetAllExecRegions() {
43   GetDefaultCodePoolInstance()->ResetExecRegion();
44   GetFunctionWrapperCodePoolInstance()->ResetExecRegion();
45 }
46 
GetDefaultCodePoolInstance()47 CodePool<ExecRegionAnonymousFactory>* GetDefaultCodePoolInstance() {
48   static auto* g_code_pool = NewForever<CodePool<ExecRegionAnonymousFactory>>();
49   return g_code_pool;
50 }
51 
52 #if defined(__BIONIC__)
GetFunctionWrapperCodePoolInstance()53 CodePool<ExecRegionElfBackedFactory>* GetFunctionWrapperCodePoolInstance() {
54   static auto* g_code_pool = NewForever<CodePool<ExecRegionElfBackedFactory>>();
55   return g_code_pool;
56 }
57 #else
GetFunctionWrapperCodePoolInstance()58 CodePool<ExecRegionAnonymousFactory>* GetFunctionWrapperCodePoolInstance() {
59   return GetDefaultCodePoolInstance();
60 }
61 #endif
62 
GetInstance()63 DataPool* DataPool::GetInstance() {
64   static auto* g_data_pool = NewForever<DataPool>();
65   return g_data_pool;
66 }
67 
68 }  // namespace berberis
69