• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma once
18 
19 #include <linux/bpf.h>
20 
21 #include <android-base/result.h>
22 #include <android-base/stringprintf.h>
23 #include <android-base/unique_fd.h>
24 #include <utils/Log.h>
25 #include "bpf/BpfUtils.h"
26 
27 namespace android {
28 namespace bpf {
29 
30 // This is a class wrapper for eBPF maps. The eBPF map is a special in-kernel
31 // data structure that stores data in <Key, Value> pairs. It can be read/write
32 // from userspace by passing syscalls with the map file descriptor. This class
33 // is used to generalize the procedure of interacting with eBPF maps and hide
34 // the implementation detail from other process. Besides the basic syscalls
35 // wrapper, it also provides some useful helper functions as well as an iterator
36 // nested class to iterate the map more easily.
37 //
38 // NOTE: A kernel eBPF map may be accessed by both kernel and userspace
39 // processes at the same time. Or if the map is pinned as a virtual file, it can
40 // be obtained by multiple eBPF map class object and accessed concurrently.
41 // Though the map class object and the underlying kernel map are thread safe, it
42 // is not safe to iterate over a map while another thread or process is deleting
43 // from it. In this case the iteration can return duplicate entries.
44 template <class Key, class Value>
45 class BpfMap {
46   public:
47     BpfMap<Key, Value>() {};
48 
49   protected:
50     // flag must be within BPF_OBJ_FLAG_MASK, ie. 0, BPF_F_RDONLY, BPF_F_WRONLY
51     BpfMap<Key, Value>(const char* pathname, uint32_t flags) {
52         int map_fd = mapRetrieve(pathname, flags);
53         if (map_fd >= 0) mMapFd.reset(map_fd);
54     }
55 
56   public:
57     explicit BpfMap<Key, Value>(const char* pathname) : BpfMap<Key, Value>(pathname, 0) {}
58 
59     BpfMap<Key, Value>(bpf_map_type map_type, uint32_t max_entries, uint32_t map_flags = 0) {
60         int map_fd = createMap(map_type, sizeof(Key), sizeof(Value), max_entries, map_flags);
61         if (map_fd >= 0) mMapFd.reset(map_fd);
62     }
63 
getFirstKey()64     base::Result<Key> getFirstKey() const {
65         Key firstKey;
66         if (getFirstMapKey(mMapFd, &firstKey)) {
67             return ErrnoErrorf("Get firstKey map {} failed", mMapFd.get());
68         }
69         return firstKey;
70     }
71 
getNextKey(const Key & key)72     base::Result<Key> getNextKey(const Key& key) const {
73         Key nextKey;
74         if (getNextMapKey(mMapFd, &key, &nextKey)) {
75             return ErrnoErrorf("Get next key of map {} failed", mMapFd.get());
76         }
77         return nextKey;
78     }
79 
writeValue(const Key & key,const Value & value,uint64_t flags)80     base::Result<void> writeValue(const Key& key, const Value& value, uint64_t flags) {
81         if (writeToMapEntry(mMapFd, &key, &value, flags)) {
82             return ErrnoErrorf("Write to map {} failed", mMapFd.get());
83         }
84         return {};
85     }
86 
readValue(const Key key)87     base::Result<Value> readValue(const Key key) const {
88         Value value;
89         if (findMapEntry(mMapFd, &key, &value)) {
90             return ErrnoErrorf("Read value of map {} failed", mMapFd.get());
91         }
92         return value;
93     }
94 
deleteValue(const Key & key)95     base::Result<void> deleteValue(const Key& key) {
96         if (deleteMapEntry(mMapFd, &key)) {
97             return ErrnoErrorf("Delete entry from map {} failed", mMapFd.get());
98         }
99         return {};
100     }
101 
102     // Function that tries to get map from a pinned path.
103     base::Result<void> init(const char* path);
104 
105     // Iterate through the map and handle each key retrieved based on the filter
106     // without modification of map content.
107     base::Result<void> iterate(
108             const std::function<base::Result<void>(const Key& key, const BpfMap<Key, Value>& map)>&
109                     filter) const;
110 
111     // Iterate through the map and get each <key, value> pair, handle each <key,
112     // value> pair based on the filter without modification of map content.
113     base::Result<void> iterateWithValue(
114             const std::function<base::Result<void>(const Key& key, const Value& value,
115                                                    const BpfMap<Key, Value>& map)>& filter) const;
116 
117     // Iterate through the map and handle each key retrieved based on the filter
118     base::Result<void> iterate(
119             const std::function<base::Result<void>(const Key& key, BpfMap<Key, Value>& map)>&
120                     filter);
121 
122     // Iterate through the map and get each <key, value> pair, handle each <key,
123     // value> pair based on the filter.
124     base::Result<void> iterateWithValue(
125             const std::function<base::Result<void>(const Key& key, const Value& value,
126                                                    BpfMap<Key, Value>& map)>& filter);
127 
getMap()128     const base::unique_fd& getMap() const { return mMapFd; };
129 
130     // Copy assignment operator
131     BpfMap<Key, Value>& operator=(const BpfMap<Key, Value>& other) {
132         if (this != &other) mMapFd.reset(fcntl(other.mMapFd.get(), F_DUPFD_CLOEXEC, 0));
133         return *this;
134     }
135 
136     // Move assignment operator
137     BpfMap<Key, Value>& operator=(BpfMap<Key, Value>&& other) noexcept {
138         mMapFd = std::move(other.mMapFd);
139         other.reset(-1);
140         return *this;
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