xref: /aosp_15_r20/external/bcc/tests/cc/test_queuestack_table.cc (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1 /*
2  * Copyright (c) 2020 Politecnico di Torino
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 "BPF.h"
18 #include "catch.hpp"
19 #include <iostream>
20 #include <linux/version.h>
21 
22 //Queue/Stack types are available only from 4.20
23 #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 20, 0)
24 TEST_CASE("queue table", "[queue_table]") {
25   const std::string BPF_PROGRAM = R"(
26     BPF_QUEUE(myqueue, int, 30);
27   )";
28 
29   ebpf::BPF bpf;
30   ebpf::StatusTuple res(0);
31   res = bpf.init(BPF_PROGRAM);
32   REQUIRE(res.ok());
33 
34   ebpf::BPFQueueStackTable<int> t = bpf.get_queuestack_table<int>("myqueue");
35 
36   SECTION("standard methods") {
37     int i, val;
38     std::string value;
39 
40     // insert elements
41     for (i=0; i<30; i++) {
42       res = t.push_value(i);
43       REQUIRE(res.ok());
44     }
45 
46     // checking head (peek)
47     res = t.get_head(val);
48     REQUIRE(res.ok());
49     REQUIRE(val == 0);
50 
51     // retrieve elements
52     for (i=0; i<30; i++) {
53       res = t.pop_value(val);
54       REQUIRE(res.ok());
55       REQUIRE(val == i);
56     }
57     // get non existing element
58     res = t.pop_value(val);
59     REQUIRE(!res.ok());
60   }
61 }
62 
63 TEST_CASE("stack table", "[stack_table]") {
64   const std::string BPF_PROGRAM = R"(
65     BPF_STACK(mystack, int, 30);
66   )";
67 
68   ebpf::BPF bpf;
69   ebpf::StatusTuple res(0);
70   res = bpf.init(BPF_PROGRAM);
71   REQUIRE(res.ok());
72 
73   ebpf::BPFQueueStackTable<int> t = bpf.get_queuestack_table<int>("mystack");
74 
75   SECTION("standard methods") {
76     int i, val;
77     std::string value;
78 
79     // insert elements
80     for (i=0; i<30; i++) {
81       res = t.push_value(i);
82       REQUIRE(res.ok());
83     }
84 
85     // checking head (peek)
86     res = t.get_head(val);
87     REQUIRE(res.ok());
88     REQUIRE(val == 29);
89 
90     // retrieve elements
91     for (i=0; i<30; i++) {
92       res = t.pop_value(val);
93       REQUIRE(res.ok());
94       REQUIRE( val == (30 - 1 - i));
95     }
96     // get non existing element
97     res = t.pop_value(val);
98     REQUIRE(!res.ok());
99   }
100 }
101 #endif
102