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 #include "berberis/base/maps_snapshot.h"
18 
19 #include <cstdint>
20 #include <cstdio>
21 #include <mutex>
22 #include <optional>
23 
24 #include "berberis/base/arena_string.h"
25 #include "berberis/base/forever_alloc.h"
26 #include "berberis/base/tracing.h"
27 
28 namespace berberis {
29 
GetInstance()30 MapsSnapshot* MapsSnapshot::GetInstance() {
31   static auto* g_maps_snapshot = PrivateNewForever<MapsSnapshot>::Alloc();
32   return g_maps_snapshot;
33 }
34 
Update()35 void MapsSnapshot::Update() {
36   std::scoped_lock lock(mutex_);
37 
38   FILE* maps_file = fopen("/proc/self/maps", "r");
39   if (!maps_file) {
40     TRACE("Error opening /proc/self/maps");
41     return;
42   }
43 
44   maps_.clear();
45 
46   char line[512], pathname[256];
47   uintptr_t start, end;
48   while (fgets(line, sizeof(line), maps_file)) {
49     // Maximum string size 255 so that we have space for the terminating '\0'.
50     int match_count = sscanf(
51         line, "%" SCNxPTR "-%" SCNxPTR " %*s %*lx %*x:%*x %*lu%*[ ]%255s", &start, &end, pathname);
52     if (match_count == 2 || match_count == 3) {
53       // If there is no pathname we still memorize the record, so that we can differentiate this
54       // case from missing mapping, e.g. when the snapshot is not up to date.
55       const char* recorded_pathname = (match_count == 3) ? pathname : "";
56       // Addresses go in the increasing order in /proc/self/maps, so we hint to add new records
57       // to the end of the map.
58       maps_.emplace_hint(
59           maps_.end(), start, Record{start, end, ArenaString{recorded_pathname, &arena_}});
60     }
61   }
62 
63   fclose(maps_file);
64 }
65 
FindMappedObjectName(uintptr_t addr)66 std::optional<const ArenaString> MapsSnapshot::FindMappedObjectName(uintptr_t addr) {
67   std::scoped_lock lock(mutex_);
68   auto next_it = maps_.upper_bound(addr);
69   if (next_it == maps_.begin()) {
70     return std::nullopt;
71   }
72   auto& rec = std::prev(next_it)->second;
73   if (addr >= rec.start && addr < rec.end) {
74     // Make sure we return a copy since the storage may be
75     // invalidated as soon as we release the lock.
76     return rec.pathname;
77   }
78   return std::nullopt;
79 }
80 
81 }  // namespace berberis
82