BpfUtils.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. * Copyright (C) 2017 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. #define LOG_TAG "BpfUtils"
  17. #include "bpf/BpfUtils.h"
  18. #include <elf.h>
  19. #include <inttypes.h>
  20. #include <linux/bpf.h>
  21. #include <linux/if_ether.h>
  22. #include <linux/in.h>
  23. #include <linux/pfkeyv2.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <sys/mman.h>
  27. #include <sys/resource.h>
  28. #include <sys/socket.h>
  29. #include <sys/stat.h>
  30. #include <sys/utsname.h>
  31. #include <sstream>
  32. #include <string>
  33. #include <android-base/properties.h>
  34. #include <android-base/unique_fd.h>
  35. #include <log/log.h>
  36. #include <netdutils/MemBlock.h>
  37. #include <netdutils/Slice.h>
  38. #include <processgroup/processgroup.h>
  39. using android::base::GetUintProperty;
  40. using android::base::unique_fd;
  41. using android::netdutils::MemBlock;
  42. using android::netdutils::Slice;
  43. // The buffer size for the buffer that records program loading logs, needs to be large enough for
  44. // the largest kernel program.
  45. namespace android {
  46. namespace bpf {
  47. /* The bpf_attr is a union which might have a much larger size then the struct we are using, while
  48. * The inline initializer only reset the field we are using and leave the reset of the memory as
  49. * is. The bpf kernel code will performs a much stricter check to ensure all unused field is 0. So
  50. * this syscall will normally fail with E2BIG if we don't do a memset to bpf_attr.
  51. */
  52. bool operator==(const StatsKey& lhs, const StatsKey& rhs) {
  53. return ((lhs.uid == rhs.uid) && (lhs.tag == rhs.tag) && (lhs.counterSet == rhs.counterSet) &&
  54. (lhs.ifaceIndex == rhs.ifaceIndex));
  55. }
  56. bool operator==(const UidTag& lhs, const UidTag& rhs) {
  57. return ((lhs.uid == rhs.uid) && (lhs.tag == rhs.tag));
  58. }
  59. bool operator==(const StatsValue& lhs, const StatsValue& rhs) {
  60. return ((lhs.rxBytes == rhs.rxBytes) && (lhs.txBytes == rhs.txBytes) &&
  61. (lhs.rxPackets == rhs.rxPackets) && (lhs.txPackets == rhs.txPackets));
  62. }
  63. int bpf(int cmd, Slice bpfAttr) {
  64. return syscall(__NR_bpf, cmd, bpfAttr.base(), bpfAttr.size());
  65. }
  66. int createMap(bpf_map_type map_type, uint32_t key_size, uint32_t value_size, uint32_t max_entries,
  67. uint32_t map_flags) {
  68. bpf_attr attr;
  69. memset(&attr, 0, sizeof(attr));
  70. attr.map_type = map_type;
  71. attr.key_size = key_size;
  72. attr.value_size = value_size;
  73. attr.max_entries = max_entries;
  74. attr.map_flags = map_flags;
  75. return bpf(BPF_MAP_CREATE, Slice(&attr, sizeof(attr)));
  76. }
  77. int writeToMapEntry(const base::unique_fd& map_fd, void* key, void* value, uint64_t flags) {
  78. bpf_attr attr;
  79. memset(&attr, 0, sizeof(attr));
  80. attr.map_fd = map_fd.get();
  81. attr.key = ptr_to_u64(key);
  82. attr.value = ptr_to_u64(value);
  83. attr.flags = flags;
  84. return bpf(BPF_MAP_UPDATE_ELEM, Slice(&attr, sizeof(attr)));
  85. }
  86. int findMapEntry(const base::unique_fd& map_fd, void* key, void* value) {
  87. bpf_attr attr;
  88. memset(&attr, 0, sizeof(attr));
  89. attr.map_fd = map_fd.get();
  90. attr.key = ptr_to_u64(key);
  91. attr.value = ptr_to_u64(value);
  92. return bpf(BPF_MAP_LOOKUP_ELEM, Slice(&attr, sizeof(attr)));
  93. }
  94. int deleteMapEntry(const base::unique_fd& map_fd, void* key) {
  95. bpf_attr attr;
  96. memset(&attr, 0, sizeof(attr));
  97. attr.map_fd = map_fd.get();
  98. attr.key = ptr_to_u64(key);
  99. return bpf(BPF_MAP_DELETE_ELEM, Slice(&attr, sizeof(attr)));
  100. }
  101. int getNextMapKey(const base::unique_fd& map_fd, void* key, void* next_key) {
  102. bpf_attr attr;
  103. memset(&attr, 0, sizeof(attr));
  104. attr.map_fd = map_fd.get();
  105. attr.key = ptr_to_u64(key);
  106. attr.next_key = ptr_to_u64(next_key);
  107. return bpf(BPF_MAP_GET_NEXT_KEY, Slice(&attr, sizeof(attr)));
  108. }
  109. int getFirstMapKey(const base::unique_fd& map_fd, void* firstKey) {
  110. bpf_attr attr;
  111. memset(&attr, 0, sizeof(attr));
  112. attr.map_fd = map_fd.get();
  113. attr.key = 0;
  114. attr.next_key = ptr_to_u64(firstKey);
  115. return bpf(BPF_MAP_GET_NEXT_KEY, Slice(&attr, sizeof(attr)));
  116. }
  117. int bpfProgLoad(bpf_prog_type prog_type, Slice bpf_insns, const char* license,
  118. uint32_t kern_version, Slice bpf_log) {
  119. bpf_attr attr;
  120. memset(&attr, 0, sizeof(attr));
  121. attr.prog_type = prog_type;
  122. attr.insns = ptr_to_u64(bpf_insns.base());
  123. attr.insn_cnt = bpf_insns.size() / sizeof(struct bpf_insn);
  124. attr.license = ptr_to_u64((void*)license);
  125. attr.log_buf = ptr_to_u64(bpf_log.base());
  126. attr.log_size = bpf_log.size();
  127. attr.log_level = DEFAULT_LOG_LEVEL;
  128. attr.kern_version = kern_version;
  129. int ret = bpf(BPF_PROG_LOAD, Slice(&attr, sizeof(attr)));
  130. if (ret < 0) {
  131. std::string prog_log = netdutils::toString(bpf_log);
  132. std::istringstream iss(prog_log);
  133. for (std::string line; std::getline(iss, line);) {
  134. ALOGE("%s", line.c_str());
  135. }
  136. }
  137. return ret;
  138. }
  139. int bpfFdPin(const base::unique_fd& map_fd, const char* pathname) {
  140. bpf_attr attr;
  141. memset(&attr, 0, sizeof(attr));
  142. attr.pathname = ptr_to_u64((void*)pathname);
  143. attr.bpf_fd = map_fd.get();
  144. return bpf(BPF_OBJ_PIN, Slice(&attr, sizeof(attr)));
  145. }
  146. int bpfFdGet(const char* pathname, uint32_t flag) {
  147. bpf_attr attr;
  148. memset(&attr, 0, sizeof(attr));
  149. attr.pathname = ptr_to_u64((void*)pathname);
  150. attr.file_flags = flag;
  151. return bpf(BPF_OBJ_GET, Slice(&attr, sizeof(attr)));
  152. }
  153. int mapRetrieve(const char* pathname, uint32_t flag) {
  154. return bpfFdGet(pathname, flag);
  155. }
  156. int attachProgram(bpf_attach_type type, uint32_t prog_fd, uint32_t cg_fd) {
  157. bpf_attr attr;
  158. memset(&attr, 0, sizeof(attr));
  159. attr.target_fd = cg_fd;
  160. attr.attach_bpf_fd = prog_fd;
  161. attr.attach_type = type;
  162. return bpf(BPF_PROG_ATTACH, Slice(&attr, sizeof(attr)));
  163. }
  164. int detachProgram(bpf_attach_type type, uint32_t cg_fd) {
  165. bpf_attr attr;
  166. memset(&attr, 0, sizeof(attr));
  167. attr.target_fd = cg_fd;
  168. attr.attach_type = type;
  169. return bpf(BPF_PROG_DETACH, Slice(&attr, sizeof(attr)));
  170. }
  171. uint64_t getSocketCookie(int sockFd) {
  172. uint64_t sock_cookie;
  173. socklen_t cookie_len = sizeof(sock_cookie);
  174. int res = getsockopt(sockFd, SOL_SOCKET, SO_COOKIE, &sock_cookie, &cookie_len);
  175. if (res < 0) {
  176. res = -errno;
  177. ALOGE("Failed to get socket cookie: %s\n", strerror(errno));
  178. errno = -res;
  179. // 0 is an invalid cookie. See sock_gen_cookie.
  180. return NONEXISTENT_COOKIE;
  181. }
  182. return sock_cookie;
  183. }
  184. int synchronizeKernelRCU() {
  185. // This is a temporary hack for network stats map swap on devices running
  186. // 4.9 kernels. The kernel code of socket release on pf_key socket will
  187. // explicitly call synchronize_rcu() which is exactly what we need.
  188. int pfSocket = socket(AF_KEY, SOCK_RAW | SOCK_CLOEXEC, PF_KEY_V2);
  189. if (pfSocket < 0) {
  190. int ret = -errno;
  191. ALOGE("create PF_KEY socket failed: %s", strerror(errno));
  192. return ret;
  193. }
  194. // When closing socket, synchronize_rcu() gets called in sock_release().
  195. if (close(pfSocket)) {
  196. int ret = -errno;
  197. ALOGE("failed to close the PF_KEY socket: %s", strerror(errno));
  198. return ret;
  199. }
  200. return 0;
  201. }
  202. int setrlimitForTest() {
  203. // Set the memory rlimit for the test process if the default MEMLOCK rlimit is not enough.
  204. struct rlimit limit = {
  205. .rlim_cur = TEST_LIMIT,
  206. .rlim_max = TEST_LIMIT,
  207. };
  208. int res = setrlimit(RLIMIT_MEMLOCK, &limit);
  209. if (res) {
  210. ALOGE("Failed to set the default MEMLOCK rlimit: %s", strerror(errno));
  211. }
  212. return res;
  213. }
  214. std::string BpfLevelToString(BpfLevel bpfLevel) {
  215. switch (bpfLevel) {
  216. case BpfLevel::NONE: return "NONE_SUPPORT";
  217. case BpfLevel::BASIC: return "BPF_LEVEL_BASIC";
  218. case BpfLevel::EXTENDED: return "BPF_LEVEL_EXTENDED";
  219. // No default statement. We want to see errors of the form:
  220. // "enumeration value 'BPF_LEVEL_xxx' not handled in switch [-Werror,-Wswitch]".
  221. }
  222. }
  223. BpfLevel getBpfSupportLevel() {
  224. struct utsname buf;
  225. int kernel_version_major;
  226. int kernel_version_minor;
  227. uint64_t api_level = GetUintProperty<uint64_t>("ro.product.first_api_level", 0);
  228. if (api_level == 0) {
  229. ALOGE("Cannot determine initial API level of the device");
  230. api_level = GetUintProperty<uint64_t>("ro.build.version.sdk", 0);
  231. }
  232. // Check if the device is shipped originally with android P.
  233. if (api_level < MINIMUM_API_REQUIRED) return BpfLevel::NONE;
  234. int ret = uname(&buf);
  235. if (ret) {
  236. return BpfLevel::NONE;
  237. }
  238. char dummy;
  239. ret = sscanf(buf.release, "%d.%d%c", &kernel_version_major, &kernel_version_minor, &dummy);
  240. // Check the device kernel version
  241. if (ret < 2) return BpfLevel::NONE;
  242. if (kernel_version_major > 4 || (kernel_version_major == 4 && kernel_version_minor >= 14))
  243. return BpfLevel::EXTENDED;
  244. if (kernel_version_major == 4 && kernel_version_minor >= 9) return BpfLevel::BASIC;
  245. return BpfLevel::NONE;
  246. }
  247. } // namespace bpf
  248. } // namespace android