1 /*
2  * Copyright (C) 2021 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 
18 #ifndef BERBERIS_TEST_UTILS_SCOPED_EXEC_REGION_H_
19 #define BERBERIS_TEST_UTILS_SCOPED_EXEC_REGION_H_
20 
21 #include "berberis/assembler/machine_code.h"
22 #include "berberis/base/bit_util.h"
23 #include "berberis/runtime_primitives/exec_region_anonymous.h"
24 #include "berberis/runtime_primitives/host_code.h"
25 
26 namespace berberis {
27 
28 class ScopedExecRegion {
29  public:
30   ScopedExecRegion() = default;
31 
ScopedExecRegion(MachineCode * code)32   explicit ScopedExecRegion(MachineCode* code) { Init(code); }
33 
34   ScopedExecRegion(const ScopedExecRegion&) = delete;
35   ScopedExecRegion& operator=(const ScopedExecRegion&) = delete;
36   ScopedExecRegion(const ScopedExecRegion&&) = delete;
37   ScopedExecRegion& operator=(const ScopedExecRegion&&) = delete;
38 
~ScopedExecRegion()39   ~ScopedExecRegion() { exec_.Free(); }
40 
Init(MachineCode * code)41   void Init(MachineCode* code) {
42     exec_ = ExecRegionAnonymousFactory::Create(code->install_size());
43     code->Install(&exec_, exec_.begin(), &recovery_map_);
44     exec_.Detach();
45   }
46 
47   template <typename T = uint8_t>
get()48   const T* get() const {
49     return bit_cast<const T*>(exec_.begin());
50   }
51 
GetHostCodeAddr()52   HostCodeAddr GetHostCodeAddr() const { return AsHostCodeAddr(AsHostCode(exec_.begin())); }
53 
recovery_map()54   [[nodiscard]] const RecoveryMap& recovery_map() const { return recovery_map_; }
55 
56  private:
57   ExecRegion exec_;
58   RecoveryMap recovery_map_;
59 };
60 
61 }  // namespace berberis
62 
63 #endif  // BERBERIS_TEST_UTILS_SCOPED_EXEC_REGION_H_
64