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