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/base/exec_region_anonymous.h"
24 
25 namespace berberis {
26 
27 class ScopedExecRegion {
28  public:
29   ScopedExecRegion() = default;
30 
ScopedExecRegion(MachineCode * code)31   explicit ScopedExecRegion(MachineCode* code) { Init(code); }
32 
33   ScopedExecRegion(const ScopedExecRegion&) = delete;
34   ScopedExecRegion& operator=(const ScopedExecRegion&) = delete;
35   ScopedExecRegion(const ScopedExecRegion&&) = delete;
36   ScopedExecRegion& operator=(const ScopedExecRegion&&) = delete;
37 
~ScopedExecRegion()38   ~ScopedExecRegion() { exec_.Free(); }
39 
Init(MachineCode * code)40   void Init(MachineCode* code) {
41     exec_ = ExecRegionAnonymousFactory::Create(code->install_size());
42     code->Install(&exec_, exec_.begin(), &recovery_map_);
43     exec_.Detach();
44   }
45 
46   template <typename T = uint8_t>
get()47   const T* get() const {
48     return bit_cast<const T*>(exec_.begin());
49   }
50 
recovery_map()51   [[nodiscard]] const RecoveryMap& recovery_map() const { return recovery_map_; }
52 
53  private:
54   ExecRegion exec_;
55   RecoveryMap recovery_map_;
56 };
57 
58 }  // namespace berberis
59 
60 #endif  // BERBERIS_TEST_UTILS_SCOPED_EXEC_REGION_H_
61