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 #ifndef BERBERIS_GUEST_OS_PRIMITIVES_GUEST_MAP_SHADOW_H_ 18 #define BERBERIS_GUEST_OS_PRIMITIVES_GUEST_MAP_SHADOW_H_ 19 20 #include <cstddef> 21 #include <mutex> 22 #include <utility> 23 24 #include "berberis/base/arena_alloc.h" 25 #include "berberis/base/arena_vector.h" 26 #include "berberis/guest_state/guest_addr.h" 27 28 namespace berberis { 29 30 enum BitValue { 31 kBitUnset, 32 kBitSet, 33 kBitMixed, 34 }; 35 36 class GuestMapShadow { 37 public: 38 GuestMapShadow(); 39 ~GuestMapShadow(); 40 41 [[nodiscard]] BitValue GetExecutable(GuestAddr start, size_t size) const; 42 43 // Check if region start..start+size is fully executable. 44 [[nodiscard]] bool IsExecutable(GuestAddr start, size_t size) const; 45 46 // Mark region start..start+size as executable. 47 void SetExecutable(GuestAddr start, size_t size); 48 49 // Mark region start..start+size as not executable. 50 void ClearExecutable(GuestAddr start, size_t size); 51 52 void RemapExecutable(GuestAddr old_start, size_t old_size, GuestAddr new_start, size_t new_size); 53 54 void AddProtectedMapping(const void* start, const void* end); 55 56 [[nodiscard]] bool IntersectsWithProtectedMapping(const void* start, const void* end); 57 58 static GuestMapShadow* GetInstance(); 59 60 private: 61 [[nodiscard]] bool IsExecAddr(GuestAddr addr) const; 62 bool SetExecAddr(GuestAddr addr, int set); 63 void CopyExecutable(GuestAddr from, size_t from_size, GuestAddr to, size_t to_size); 64 65 uint8_t* shadow_; 66 Arena arena_; 67 std::mutex mutex_; 68 // Mappings protected from guest tampering. 69 // Warning: it's not optimized for quick look up since 70 // we don't expect to store more than a few mappings. 71 ArenaVector<std::pair<const void*, const void*>> protected_maps_; 72 }; 73 74 } // namespace berberis 75 76 #endif // BERBERIS_GUEST_OS_PRIMITIVES_GUEST_MAP_SHADOW_H_ 77