Skip to content

Commit 6869033

Browse files
committed
refactor: use unique_ptr for BPF resource pointers
1 parent 2a3c9b4 commit 6869033

File tree

2 files changed

+16
-19
lines changed

2 files changed

+16
-19
lines changed

src/bpf_program.cpp

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@ static void configure_bpf_program(knock_bpf* skel, const knock_config& config)
1313
static void load_bpf_program(knock_bpf* skel)
1414
{
1515
if (knock_bpf__load(skel) != 0) {
16-
knock_bpf__destroy(skel);
17-
skel = nullptr;
1816
throw BpfError("Failed to load BPF program");
1917
}
2018
}
@@ -30,26 +28,16 @@ static void load_bpf_program(knock_bpf* skel)
3028

3129
BpfProgram::BpfProgram(const knock_config& config)
3230
{
33-
skel = open_bpf_program();
34-
load_bpf_program(skel);
35-
configure_bpf_program(skel, config);
31+
skel.reset(open_bpf_program());
32+
load_bpf_program(skel.get());
33+
configure_bpf_program(skel.get(), config);
3634
}
3735

38-
BpfProgram::~BpfProgram()
39-
{
40-
if (link) {
41-
bpf_link__destroy(link);
42-
link = nullptr;
43-
}
44-
if (skel) {
45-
knock_bpf__destroy(skel);
46-
skel = nullptr;
47-
}
48-
}
36+
BpfProgram::~BpfProgram() = default;
4937

5038
void BpfProgram::attach_xdp(int ifindex, const std::string& interface)
5139
{
52-
link = bpf_program__attach_xdp(skel->progs.knock, ifindex);
40+
link.reset(bpf_program__attach_xdp(skel->progs.knock, ifindex));
5341
if (!link) {
5442
throw BpfError("Failed to attach XDP program to interface " + interface);
5543
}

src/bpf_program.hpp

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,20 @@
22
#include "knock.skel.h"
33
#include "knock.h"
44
#include <string>
5+
#include <memory>
6+
7+
struct BpfLinkDeleter {
8+
void operator()(bpf_link* link)
9+
{
10+
if (link)
11+
bpf_link__destroy(link);
12+
}
13+
};
514

615
class BpfProgram {
716
private:
8-
knock_bpf* skel = nullptr;
9-
bpf_link* link = nullptr;
17+
std::unique_ptr<knock_bpf, void (*)(knock_bpf*)> skel { nullptr, knock_bpf__destroy };
18+
std::unique_ptr<bpf_link, BpfLinkDeleter> link;
1019

1120
public:
1221
explicit BpfProgram(const knock_config& config);

0 commit comments

Comments
 (0)