1 /*
2  * Copyright (C) 2018 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 BPF_BPFMAP_H
18 #define BPF_BPFMAP_H
19 
20 #include <linux/bpf.h>
21 
22 #include <android-base/result.h>
23 #include <android-base/stringprintf.h>
24 #include <android-base/unique_fd.h>
25 #include <utils/Log.h>
26 #include "bpf/BpfUtils.h"
27 
28 namespace android {
29 namespace bpf {
30 
31 // This is a class wrapper for eBPF maps. The eBPF map is a special in-kernel
32 // data structure that stores data in <Key, Value> pairs. It can be read/write
33 // from userspace by passing syscalls with the map file descriptor. This class
34 // is used to generalize the procedure of interacting with eBPF maps and hide
35 // the implementation detail from other process. Besides the basic syscalls
36 // wrapper, it also provides some useful helper functions as well as an iterator
37 // nested class to iterate the map more easily.
38 //
39 // NOTE: A kernel eBPF map may be accessed by both kernel and userspace
40 // processes at the same time. Or if the map is pinned as a virtual file, it can
41 // be obtained by multiple eBPF map class object and accessed concurrently.
42 // Though the map class object and the underlying kernel map are thread safe, it
43 // is not safe to iterate over a map while another thread or process is deleting
44 // from it. In this case the iteration can return duplicate entries.
45 template <class Key, class Value>
46 class BpfMap {
47   public:
48     BpfMap<Key, Value>() {};
49 
50   protected:
51     // flag must be within BPF_OBJ_FLAG_MASK, ie. 0, BPF_F_RDONLY, BPF_F_WRONLY
52     BpfMap<Key, Value>(const char* pathname, uint32_t flags) {
53         int map_fd = mapRetrieve(pathname, flags);
54         if (map_fd >= 0) mMapFd.reset(map_fd);
55     }
56 
57   public:
58     explicit BpfMap<Key, Value>(const char* pathname) : BpfMap<Key, Value>(pathname, 0) {}
59 
60     BpfMap<Key, Value>(bpf_map_type map_type, uint32_t max_entries, uint32_t map_flags = 0) {
61         int map_fd = createMap(map_type, sizeof(Key), sizeof(Value), max_entries, map_flags);
62         if (map_fd >= 0) mMapFd.reset(map_fd);
63     }
64 
getFirstKey()65     base::Result<Key> getFirstKey() const {
66         Key firstKey;
67         if (getFirstMapKey(mMapFd, &firstKey)) {
68             return ErrnoErrorf("Get firstKey map {} failed", mMapFd.get());
69         }
70         return firstKey;
71     }
72 
getNextKey(const Key & key)73     base::Result<Key> getNextKey(const Key& key) const {
74         Key nextKey;
75         if (getNextMapKey(mMapFd, &key, &nextKey)) {
76             return ErrnoErrorf("Get next key of map {} failed", mMapFd.get());
77         }
78         return nextKey;
79     }
80 
writeValue(const Key & key,const Value & value,uint64_t flags)81     base::Result<void> writeValue(const Key& key, const Value& value, uint64_t flags) {
82         if (writeToMapEntry(mMapFd, &key, &value, flags)) {
83             return ErrnoErrorf("Write to map {} failed", mMapFd.get());
84         }
85         return {};
86     }
87 
readValue(const Key key)88     base::Result<Value> readValue(const Key key) const {
89         Value value;
90         if (findMapEntry(mMapFd, &key, &value)) {
91             return ErrnoErrorf("Read value of map {} failed", mMapFd.get());
92         }
93         return value;
94     }
95 
deleteValue(const Key & key)96     base::Result<void> deleteValue(const Key& key) {
97         if (deleteMapEntry(mMapFd, &key)) {
98             return ErrnoErrorf("Delete entry from map {} failed", mMapFd.get());
99         }
100         return {};
101     }
102 
103     // Function that tries to get map from a pinned path.
104     base::Result<void> init(const char* path);
105 
106     // Iterate through the map and handle each key retrieved based on the filter
107     // without modification of map content.
108     base::Result<void> iterate(
109             const std::function<base::Result<void>(const Key& key, const BpfMap<Key, Value>& map)>&
110                     filter) const;
111 
112     // Iterate through the map and get each <key, value> pair, handle each <key,
113     // value> pair based on the filter without modification of map content.
114     base::Result<void> iterateWithValue(
115             const std::function<base::Result<void>(const Key& key, const Value& value,
116                                                    const BpfMap<Key, Value>& map)>& filter) const;
117 
118     // Iterate through the map and handle each key retrieved based on the filter
119     base::Result<void> iterate(
120             const std::function<base::Result<void>(const Key& key, BpfMap<Key, Value>& map)>&
121                     filter);
122 
123     // Iterate through the map and get each <key, value> pair, handle each <key,
124     // value> pair based on the filter.
125     base::Result<void> iterateWithValue(
126             const std::function<base::Result<void>(const Key& key, const Value& value,
127                                                    BpfMap<Key, Value>& map)>& filter);
128 
getMap()129     const base::unique_fd& getMap() const { return mMapFd; };
130 
131     // Copy assignment operator
132     BpfMap<Key, Value>& operator=(const BpfMap<Key, Value>& other) {
133         if (this != &other) mMapFd.reset(fcntl(other.mMapFd.get(), F_DUPFD_CLOEXEC, 0));
134         return *this;
135     }
136 
137     // Move constructor
138     void operator=(BpfMap<Key, Value>&& other) noexcept {
139         mMapFd = std::move(other.mMapFd);
140         other.reset(-1);
141     }
142 
143     void reset(base::unique_fd fd) = delete;
144 
reset(int fd)145     void reset(int fd) { mMapFd.reset(fd); }
146 
isValid()147     bool isValid() const { return mMapFd != -1; }
148 
clear()149     base::Result<void> clear() {
150         while (true) {
151             auto key = getFirstKey();
152             if (!key.ok()) {
153                 if (key.error().code() == ENOENT) return {};  // empty: success
154                 return key.error();                           // Anything else is an error
155             }
156             auto res = deleteValue(key.value());
157             if (!res.ok()) {
158                 // Someone else could have deleted the key, so ignore ENOENT
159                 if (res.error().code() == ENOENT) continue;
160                 ALOGE("Failed to delete data %s", strerror(res.error().code()));
161                 return res.error();
162             }
163         }
164     }
165 
isEmpty()166     base::Result<bool> isEmpty() const {
167         auto key = getFirstKey();
168         if (!key.ok()) {
169             // Return error code ENOENT means the map is empty
170             if (key.error().code() == ENOENT) return true;
171             return key.error();
172         }
173         return false;
174     }
175 
176   private:
177     base::unique_fd mMapFd;
178 };
179 
180 template <class Key, class Value>
init(const char * path)181 base::Result<void> BpfMap<Key, Value>::init(const char* path) {
182     mMapFd = base::unique_fd(mapRetrieveRW(path));
183     if (mMapFd == -1) {
184         return ErrnoErrorf("Pinned map not accessible or does not exist: ({})", path);
185     }
186     return {};
187 }
188 
189 template <class Key, class Value>
iterate(const std::function<base::Result<void> (const Key & key,const BpfMap<Key,Value> & map)> & filter)190 base::Result<void> BpfMap<Key, Value>::iterate(
191         const std::function<base::Result<void>(const Key& key, const BpfMap<Key, Value>& map)>&
192                 filter) const {
193     base::Result<Key> curKey = getFirstKey();
194     while (curKey.ok()) {
195         const base::Result<Key>& nextKey = getNextKey(curKey.value());
196         base::Result<void> status = filter(curKey.value(), *this);
197         if (!status.ok()) return status;
198         curKey = nextKey;
199     }
200     if (curKey.error().code() == ENOENT) return {};
201     return curKey.error();
202 }
203 
204 template <class Key, class Value>
iterateWithValue(const std::function<base::Result<void> (const Key & key,const Value & value,const BpfMap<Key,Value> & map)> & filter)205 base::Result<void> BpfMap<Key, Value>::iterateWithValue(
206         const std::function<base::Result<void>(const Key& key, const Value& value,
207                                                const BpfMap<Key, Value>& map)>& filter) const {
208     base::Result<Key> curKey = getFirstKey();
209     while (curKey.ok()) {
210         const base::Result<Key>& nextKey = getNextKey(curKey.value());
211         base::Result<Value> curValue = readValue(curKey.value());
212         if (!curValue.ok()) return curValue.error();
213         base::Result<void> status = filter(curKey.value(), curValue.value(), *this);
214         if (!status.ok()) return status;
215         curKey = nextKey;
216     }
217     if (curKey.error().code() == ENOENT) return {};
218     return curKey.error();
219 }
220 
221 template <class Key, class Value>
iterate(const std::function<base::Result<void> (const Key & key,BpfMap<Key,Value> & map)> & filter)222 base::Result<void> BpfMap<Key, Value>::iterate(
223         const std::function<base::Result<void>(const Key& key, BpfMap<Key, Value>& map)>& filter) {
224     base::Result<Key> curKey = getFirstKey();
225     while (curKey.ok()) {
226         const base::Result<Key>& nextKey = getNextKey(curKey.value());
227         base::Result<void> status = filter(curKey.value(), *this);
228         if (!status.ok()) return status;
229         curKey = nextKey;
230     }
231     if (curKey.error().code() == ENOENT) return {};
232     return curKey.error();
233 }
234 
235 template <class Key, class Value>
iterateWithValue(const std::function<base::Result<void> (const Key & key,const Value & value,BpfMap<Key,Value> & map)> & filter)236 base::Result<void> BpfMap<Key, Value>::iterateWithValue(
237         const std::function<base::Result<void>(const Key& key, const Value& value,
238                                                BpfMap<Key, Value>& map)>& filter) {
239     base::Result<Key> curKey = getFirstKey();
240     while (curKey.ok()) {
241         const base::Result<Key>& nextKey = getNextKey(curKey.value());
242         base::Result<Value> curValue = readValue(curKey.value());
243         if (!curValue.ok()) return curValue.error();
244         base::Result<void> status = filter(curKey.value(), curValue.value(), *this);
245         if (!status.ok()) return status;
246         curKey = nextKey;
247     }
248     if (curKey.error().code() == ENOENT) return {};
249     return curKey.error();
250 }
251 
252 template <class Key, class Value>
253 class BpfMapRO : public BpfMap<Key, Value> {
254   public:
255     explicit BpfMapRO<Key, Value>(const char* pathname)
256         : BpfMap<Key, Value>(pathname, BPF_F_RDONLY) {}
257 };
258 
259 }  // namespace bpf
260 }  // namespace android
261 
262 #endif
263