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 #include <android-base/macros.h> 18 #include <gtest/gtest.h> 19 #include <stdlib.h> 20 #include <unistd.h> 21 #include <iostream> 22 #include "include/bpf/BpfMap.h" 23 #include "include/bpf/BpfUtils.h" 24 #include "include/libbpf_android.h" 25 26 using ::testing::Test; 27 28 constexpr const char tp_prog_path[] = 29 "/sys/fs/bpf/prog_bpf_load_tp_prog_tracepoint_sched_sched_switch"; 30 constexpr const char tp_map_path[] = "/sys/fs/bpf/map_bpf_load_tp_prog_cpu_pid"; 31 32 namespace android { 33 namespace bpf { 34 35 class BpfLoadTest : public testing::Test { 36 protected: 37 BpfLoadTest() {} 38 int mProgFd, mMapFd; 39 40 void SetUp() { 41 SKIP_IF_BPF_NOT_SUPPORTED; 42 43 unlink(tp_prog_path); 44 unlink(tp_map_path); 45 46 EXPECT_EQ(android::bpf::loadProg("/system/etc/bpf/bpf_load_tp_prog.o"), 0); 47 48 mProgFd = bpf_obj_get(tp_prog_path); 49 EXPECT_GT(mProgFd, 0); 50 51 mMapFd = bpf_obj_get(tp_map_path); 52 EXPECT_GT(mMapFd, 0); 53 54 int ret = bpf_attach_tracepoint(mProgFd, "sched", "sched_switch"); 55 EXPECT_NE(ret, 0); 56 } 57 58 void TearDown() { 59 SKIP_IF_BPF_NOT_SUPPORTED; 60 61 close(mProgFd); 62 close(mMapFd); 63 unlink(tp_prog_path); 64 unlink(tp_map_path); 65 } 66 67 void checkMapNonZero() { 68 // The test program installs a tracepoint on sched:sched_switch 69 // and expects the kernel to populate a PID corresponding to CPU 70 android::bpf::BpfMap<uint32_t, uint32_t> m(mMapFd); 71 72 // Wait for program to run a little 73 sleep(1); 74 75 int non_zero = 0; 76 const auto iterFunc = [&non_zero](const uint32_t& key, const uint32_t& val, 77 BpfMap<uint32_t, uint32_t>& map) { 78 if (val && !non_zero) { 79 non_zero = 1; 80 } 81 82 UNUSED(key); 83 UNUSED(map); 84 return android::netdutils::status::ok; 85 }; 86 87 EXPECT_OK(m.iterateWithValue(iterFunc)); 88 EXPECT_EQ(non_zero, 1); 89 } 90 }; 91 92 TEST_F(BpfLoadTest, bpfCheckMap) { 93 SKIP_IF_BPF_NOT_SUPPORTED; 94 95 checkMapNonZero(); 96 } 97 98 } // namespace bpf 99 } // namespace android 100