-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
mod.rs
204 lines (190 loc) · 7.88 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! SPDX-License-Identifier: MIT
//!
//! Copyright (c) 2023, eunomia-bpf
//! All rights reserved.
//!
use std::{collections::HashMap, sync::Arc};
use crate::{
btf_container::BtfContainer,
elf_container::ElfContainer,
meta::{EunomiaObjectMeta, RunnerConfig},
skeleton::preload::{
attach::{attach_perf_event, attach_tc, attach_xdp, AttachLink},
section_loader::load_section_data_with_skel_value,
},
};
use anyhow::{anyhow, bail, Context, Result};
use libbpf_rs::OpenObject;
use log::debug;
use object::{Object, ObjectSection};
use super::{handle::PollingHandle, BpfSkeleton};
pub(crate) mod attach;
pub(crate) mod section_loader;
/// Represents an initialized bpf skeleton. It's waiting for the loading and attaching of bpf programs
pub struct PreLoadBpfSkeleton {
/// data storage
/// meta data control the behavior of ebpf program:
/// eg. types of the eBPF maps and prog, export data types
pub(crate) meta: EunomiaObjectMeta,
/// config of eunomia itself,
/// for how we creating, loading and interacting with the eBPF program
/// eg. poll maps timeout in ms
pub(crate) config_data: RunnerConfig,
pub(crate) bpf_object: OpenObject,
// Btf for the loaded program
pub(crate) btf: BtfContainer,
// Value sizes of maps this program hold
// This is a workaround for libbpf-rs not exposing bpf_map* in OpenMap
pub(crate) map_value_sizes: HashMap<String, u32>,
pub(crate) raw_elf: ElfContainer,
}
impl PreLoadBpfSkeleton {
/// start running the ebpf program
/// load and attach the ebpf program to the kernel to run the ebpf program
/// if the ebpf program has maps to export to user space, you need to call
/// the wait and export.
pub fn load_and_attach(mut self) -> Result<BpfSkeleton> {
// This function differs from the C++ version `int bpf_skeleton::load_and_attach_prog(void)`
// Because we put the call to bpf_object_open in `BpfSkeletonBuilder::build`
// So Here are just the calls to load and attach
debug!(
"Section names of ELF: {:?}",
self.raw_elf
.borrow_elf()
.sections()
.map(|v| v.name().map(|t| t.to_string()))
.collect::<Vec<_>>()
);
// Initialize data for sections
for section in self.meta.bpf_skel.data_sections.iter() {
debug!("Loading section: {:?}", section);
let map_meta = match section.name.as_str() {
".rodata" => self
.meta
.bpf_skel
.find_map_by_ident("rodata")
.ok_or_else(|| {
anyhow!("Failed to find map with ident `rodata` for section .rodata")
})?,
".bss" => self.meta.bpf_skel.find_map_by_ident("bss").ok_or_else(|| {
anyhow!("Failed to find map with ident `bss` for section .bss")
})?,
s => bail!("Unsupported section: {}", s),
};
let map_name = map_meta.name.as_str();
let map = self.bpf_object.map_mut(map_name).ok_or_else(|| {
anyhow!(
"Map named `{}` doesn't exist, cannot map section `{}`",
map_name,
section.name
)
})?;
// Set a buffer to hold the data
let buffer_size = *self
.map_value_sizes
.get(map_name)
.ok_or_else(|| anyhow!("Map name {} not found in value sizes", map_name))?
as usize;
debug!("Buffer size: {}", buffer_size);
let mut buffer = if let Some(v) = self
.raw_elf
.borrow_elf()
.section_data_by_name(§ion.name)
{
debug!("Using buffer from ELF");
v.to_vec()
} else {
debug!("Using empty buffer");
vec![0; buffer_size]
};
if buffer.len() < buffer_size {
// Ensure correct size for zero-filled sections, e.g bss
buffer.resize(buffer_size, 0);
}
debug!("Buffer before filling: {:?}", buffer);
load_section_data_with_skel_value(self.btf.borrow_btf(), section, &mut buffer)
.with_context(|| anyhow!("Failed to load section {}", section.name))?;
debug!("Loaded buffer: {:?}", buffer);
map.set_initial_value(&buffer[..])
.map_err(|e| anyhow!("Failed to set initial value of map `{}`: {}", map_name, e))?;
}
let mut bpf_object = self
.bpf_object
.load()
.with_context(|| anyhow!("Failed to load bpf object"))?;
// Next steps are attaching...
let mut not_attached = vec![];
let mut links = vec![];
for prog_meta in self.meta.bpf_skel.progs.iter() {
let bpf_prog = bpf_object
.prog_mut(&prog_meta.name)
.ok_or_else(|| anyhow!("Program named `{}` not found in libbpf", prog_meta.name))?;
match bpf_prog.attach() {
Ok(link) => links.push(AttachLink::BpfLink(link)),
// EOPNOTSUPP 95 Operation not supported
Err(_) if errno::errno().0 == 95 => {
// Not supported for auto-attaching, needs manually operations
not_attached.push(prog_meta);
continue;
}
Err(err) => bail!("Failed to attach program `{}`: {}", prog_meta.name, err),
};
}
for prog_meta in not_attached.into_iter() {
let bpf_prog = bpf_object
.prog_mut(&prog_meta.name)
.ok_or_else(|| anyhow!("Program named `{}` not found", prog_meta.name))?;
match bpf_prog.section() {
"tc" => links.push(attach_tc(bpf_prog, prog_meta).with_context(|| {
anyhow!("Failed to attach tc program `{}`", prog_meta.name)
})?),
"xdp" => links.push(attach_xdp(bpf_prog, prog_meta).with_context(|| {
anyhow!("Failed to attach xdp program `{}`", prog_meta.name)
})?),
"perf_event" => {
let mut perf_links =
attach_perf_event(bpf_prog, prog_meta).with_context(|| {
anyhow!("Failed to attach perf event program `{}`", prog_meta.name)
})?;
links.append(&mut perf_links);
}
s => bail!("Unsupported attach type: {}", s),
}
}
Ok(BpfSkeleton {
handle: PollingHandle::new(),
meta: self.meta,
config_data: self.config_data,
btf: Arc::new(self.btf),
links,
prog: bpf_object,
})
}
}
#[cfg(test)]
#[cfg(not(feature = "no-load-bpf-tests"))]
mod tests {
use crate::{
meta::ComposedObject, skeleton::builder::BpfSkeletonBuilder, tests::get_assets_dir,
};
#[test]
fn test_load_and_attach() {
let skel: ComposedObject = serde_json::from_str(
&std::fs::read_to_string(get_assets_dir().join("bootstrap.json")).unwrap(),
)
.unwrap();
let pre_load_skel = BpfSkeletonBuilder::from_json_package(&skel, None)
.build()
.unwrap();
let loaded = pre_load_skel.load_and_attach().unwrap();
let prog = loaded.prog;
for map_meta in skel.meta.bpf_skel.maps.iter() {
let _map_bpf = prog.map(map_meta.name.as_str()).unwrap();
}
for prog_meta in skel.meta.bpf_skel.progs.iter() {
let prog_bpf = prog.prog(&prog_meta.name).unwrap();
assert_eq!(prog_bpf.section(), prog_meta.attach);
}
assert_eq!(loaded.links.len(), skel.meta.bpf_skel.progs.len());
}
}