1 /*
2  * Copyright (C) 2024 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_BASE_INCLUDE_BERBERIS_BASE_MAPS_SNAPSHOT_H_
18 #define BERBERIS_BASE_INCLUDE_BERBERIS_BASE_MAPS_SNAPSHOT_H_
19 
20 #include <cstdint>
21 #include <mutex>
22 #include <optional>
23 
24 #include "berberis/base/arena_alloc.h"
25 #include "berberis/base/arena_map.h"
26 #include "berberis/base/arena_string.h"
27 #include "berberis/base/forever_alloc.h"  // friend PrivateNewForever
28 
29 namespace berberis {
30 
31 // Stores snapshot mappings from /proc/self/maps for faster access.
32 // Can contain stale records which is fine for profiling or heuristics,
33 // but do NOT use it where reliable mapping information is required.
34 // Call Update() to reread /proc/self/maps.
35 // Thread-safe, doesn't use malloc.
36 class MapsSnapshot {
37  public:
38   static MapsSnapshot* GetInstance();
39   void Update();
40   // It's important that we return const ArenaString, since arena isn't thread-safe, and we should
41   // NOT be triggering re-allocations from outside of this class.
42   std::optional<const ArenaString> FindMappedObjectName(uintptr_t addr);
ClearForTesting()43   void ClearForTesting() {
44     std::scoped_lock lock(mutex_);
45     maps_.clear();
46   };
47 
48  private:
MapsSnapshot()49   MapsSnapshot() : arena_(), mutex_(), maps_(&arena_) {};
50   struct Record {
51     uintptr_t start;
52     uintptr_t end;
53     ArenaString pathname;
54   };
55   Arena arena_;
56   std::mutex mutex_;
57   ArenaMap<uintptr_t, Record> maps_;
58 
59   friend PrivateNewForever<MapsSnapshot>;
60 };
61 
62 }  // namespace berberis
63 
64 #endif  // BERBERIS_BASE_INCLUDE_BERBERIS_BASE_MAPS_SNAPSHOT_H_
65