1 /*
2  * Copyright (C) 2022 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/file.h>
18 #include <android-base/macros.h>
19 #include <android-base/result-gmock.h>
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 
25 #include "BpfSyscallWrappers.h"
26 #include "bpf/BpfRingbuf.h"
27 #include "bpf/BpfUtils.h"
28 #include "bpf/KernelUtils.h"
29 
30 #define TEST_RINGBUF_MAGIC_NUM 12345
31 
32 namespace android {
33 namespace bpf {
34 using ::android::base::testing::HasError;
35 using ::android::base::testing::HasValue;
36 using ::android::base::testing::WithCode;
37 using ::testing::AllOf;
38 using ::testing::Gt;
39 using ::testing::HasSubstr;
40 using ::testing::Lt;
41 
42 class BpfRingbufTest : public ::testing::Test {
43  protected:
BpfRingbufTest()44   BpfRingbufTest()
45       : mProgPath("/sys/fs/bpf/prog_bpfRingbufProg_skfilter_ringbuf_test"),
46         mRingbufPath("/sys/fs/bpf/map_bpfRingbufProg_test_ringbuf") {}
47 
SetUp()48   void SetUp() {
49     if (!android::bpf::isAtLeastKernelVersion(5, 8, 0)) {
50       GTEST_SKIP() << "BPF ring buffers not supported below 5.8";
51     }
52 
53     errno = 0;
54     mProgram.reset(retrieveProgram(mProgPath.c_str()));
55     EXPECT_EQ(errno, 0);
56     ASSERT_GE(mProgram.get(), 0)
57         << mProgPath << " was either not found or inaccessible.";
58   }
59 
RunProgram()60   void RunProgram() {
61     char fake_skb[128] = {};
62     EXPECT_EQ(runProgram(mProgram, fake_skb, sizeof(fake_skb)), 0);
63   }
64 
RunTestN(int n)65   void RunTestN(int n) {
66     int run_count = 0;
67     uint64_t output = 0;
68     auto callback = [&](const uint64_t& value) {
69       output = value;
70       run_count++;
71     };
72 
73     auto result = BpfRingbuf<uint64_t>::Create(mRingbufPath.c_str());
74     ASSERT_RESULT_OK(result);
75     EXPECT_TRUE(result.value()->isEmpty());
76 
77     struct timespec t1, t2;
78     EXPECT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &t1));
79     EXPECT_FALSE(result.value()->wait(1000 /*ms*/));  // false because wait should timeout
80     EXPECT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &t2));
81     long long time1 = t1.tv_sec * 1000000000LL + t1.tv_nsec;
82     long long time2 = t2.tv_sec * 1000000000LL + t2.tv_nsec;
83     EXPECT_GE(time2 - time1, 1000000000 /*ns*/);  // 1000 ms as ns
84 
85     for (int i = 0; i < n; i++) {
86       RunProgram();
87     }
88 
89     EXPECT_FALSE(result.value()->isEmpty());
90 
91     EXPECT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &t1));
92     EXPECT_TRUE(result.value()->wait());
93     EXPECT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &t2));
94     time1 = t1.tv_sec * 1000000000LL + t1.tv_nsec;
95     time2 = t2.tv_sec * 1000000000LL + t2.tv_nsec;
96     EXPECT_LE(time2 - time1, 1000000 /*ns*/);  // in x86 CF testing < 5000 ns
97 
98     EXPECT_THAT(result.value()->ConsumeAll(callback), HasValue(n));
99     EXPECT_TRUE(result.value()->isEmpty());
100     EXPECT_EQ(output, TEST_RINGBUF_MAGIC_NUM);
101     EXPECT_EQ(run_count, n);
102   }
103 
104   std::string mProgPath;
105   std::string mRingbufPath;
106   android::base::unique_fd mProgram;
107 };
108 
TEST_F(BpfRingbufTest,ConsumeSingle)109 TEST_F(BpfRingbufTest, ConsumeSingle) { RunTestN(1); }
TEST_F(BpfRingbufTest,ConsumeMultiple)110 TEST_F(BpfRingbufTest, ConsumeMultiple) { RunTestN(3); }
111 
TEST_F(BpfRingbufTest,FillAndWrap)112 TEST_F(BpfRingbufTest, FillAndWrap) {
113   int run_count = 0;
114   auto callback = [&](const uint64_t&) { run_count++; };
115 
116   auto result = BpfRingbuf<uint64_t>::Create(mRingbufPath.c_str());
117   ASSERT_RESULT_OK(result);
118 
119   // 4kb buffer with 16 byte payloads (8 byte data, 8 byte header) should fill
120   // after 255 iterations. Exceed that so that some events are dropped.
121   constexpr int iterations = 300;
122   for (int i = 0; i < iterations; i++) {
123     RunProgram();
124   }
125 
126   // Some events were dropped, but consume all that succeeded.
127   EXPECT_THAT(result.value()->ConsumeAll(callback),
128               HasValue(AllOf(Gt(250), Lt(260))));
129   EXPECT_THAT(run_count, AllOf(Gt(250), Lt(260)));
130 
131   // After consuming everything, we should be able to use the ring buffer again.
132   run_count = 0;
133   RunProgram();
134   EXPECT_THAT(result.value()->ConsumeAll(callback), HasValue(1));
135   EXPECT_EQ(run_count, 1);
136 }
137 
TEST_F(BpfRingbufTest,WrongTypeSize)138 TEST_F(BpfRingbufTest, WrongTypeSize) {
139   // The program under test writes 8-byte uint64_t values so a ringbuffer for
140   // 1-byte uint8_t values will fail to read from it. Note that the map_def does
141   // not specify the value size, so we fail on read, not creation.
142   auto result = BpfRingbuf<uint8_t>::Create(mRingbufPath.c_str());
143   ASSERT_RESULT_OK(result);
144 
145   RunProgram();
146 
147   EXPECT_THAT(result.value()->ConsumeAll([](const uint8_t&) {}),
148               HasError(WithCode(EMSGSIZE)));
149 }
150 
TEST_F(BpfRingbufTest,InvalidPath)151 TEST_F(BpfRingbufTest, InvalidPath) {
152   EXPECT_THAT(BpfRingbuf<int>::Create("/sys/fs/bpf/bad_path"),
153               HasError(WithCode(ENOENT)));
154 }
155 
156 }  // namespace bpf
157 }  // namespace android
158