Skip to content

Commit 83b01c2

Browse files
committed
feat(aya): Add task storage map type (in the user-space)
Task storage is a type of map which uses `task_struct` kernel type as a key. When the task (process) stops, the corresponding entry is automatically removed. This change add support only in the user-space and tests the functionality with a C program.
1 parent e96431f commit 83b01c2

File tree

11 files changed

+369
-1
lines changed

11 files changed

+369
-1
lines changed

aya/src/bpf.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -730,6 +730,7 @@ fn parse_map(
730730
BPF_MAP_TYPE_DEVMAP => Map::DevMap(map),
731731
BPF_MAP_TYPE_DEVMAP_HASH => Map::DevMapHash(map),
732732
BPF_MAP_TYPE_XSKMAP => Map::XskMap(map),
733+
BPF_MAP_TYPE_TASK_STORAGE => Map::TaskStorage(map),
733734
m_type => {
734735
if allow_unsupported_maps {
735736
Map::Unsupported(map)

aya/src/maps/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ pub mod ring_buf;
8787
pub mod sock;
8888
pub mod stack;
8989
pub mod stack_trace;
90+
pub mod task_storage;
9091
pub mod xdp;
9192

9293
pub use array::{Array, PerCpuArray, ProgramArray};
@@ -103,6 +104,7 @@ pub use ring_buf::RingBuf;
103104
pub use sock::{SockHash, SockMap};
104105
pub use stack::Stack;
105106
pub use stack_trace::StackTraceMap;
107+
pub use task_storage::TaskStorage;
106108
pub use xdp::{CpuMap, DevMap, DevMapHash, XskMap};
107109

108110
#[derive(Error, Debug)]
@@ -312,6 +314,8 @@ pub enum Map {
312314
Stack(MapData),
313315
/// A [`StackTraceMap`] map.
314316
StackTraceMap(MapData),
317+
/// A [`TaskStorage`] map.
318+
TaskStorage(MapData),
315319
/// An unsupported map type.
316320
Unsupported(MapData),
317321
/// A [`XskMap`] map.
@@ -341,6 +345,7 @@ impl Map {
341345
Self::SockMap(map) => map.obj.map_type(),
342346
Self::Stack(map) => map.obj.map_type(),
343347
Self::StackTraceMap(map) => map.obj.map_type(),
348+
Self::TaskStorage(map) => map.obj.map_type(),
344349
Self::Unsupported(map) => map.obj.map_type(),
345350
Self::XskMap(map) => map.obj.map_type(),
346351
}
@@ -371,6 +376,7 @@ impl Map {
371376
Self::SockMap(map) => map.pin(path),
372377
Self::Stack(map) => map.pin(path),
373378
Self::StackTraceMap(map) => map.pin(path),
379+
Self::TaskStorage(map) => map.pin(path),
374380
Self::Unsupported(map) => map.pin(path),
375381
Self::XskMap(map) => map.pin(path),
376382
}
@@ -420,6 +426,7 @@ impl_map_pin!((V) {
420426
BloomFilter,
421427
Queue,
422428
Stack,
429+
TaskStorage,
423430
});
424431

425432
impl_map_pin!((K, V) {
@@ -502,6 +509,7 @@ impl_try_from_map!((V) {
502509
Queue,
503510
SockHash,
504511
Stack,
512+
TaskStorage,
505513
});
506514

507515
impl_try_from_map!((K, V) {

aya/src/maps/task_storage.rs

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
//! Task storage.
2+
use std::{
3+
borrow::Borrow,
4+
marker::PhantomData,
5+
os::fd::{AsFd, AsRawFd},
6+
};
7+
8+
use crate::{
9+
Pod,
10+
maps::{MapData, MapError, check_kv_size},
11+
sys::{PidFd, SyscallError, bpf_map_lookup_elem},
12+
};
13+
14+
/// Task storage is a type of map which uses `task_struct` kernel type as a
15+
/// key. When the task (process) stops, the corresponding entry is
16+
/// automatically removed.
17+
///
18+
/// # Minimum kernel version
19+
///
20+
/// The minimum kernel version required to use this feature is 5.12.
21+
///
22+
/// # Examples
23+
///
24+
/// ```no_run
25+
/// # let mut ebpf = aya::Ebpf::load(&[])?;
26+
/// use aya::maps::TaskStorage;
27+
///
28+
/// let mut task_storage: TaskStorage<_, u32> = TaskStorage::try_from(ebpf.map_mut("TASK_STORAGE").unwrap())?;
29+
///
30+
/// let pid = 0;
31+
/// let value = task_storage.get(&pid, 0)?;
32+
/// # Ok::<(), aya::EbpfError>(())
33+
/// ```
34+
#[doc(alias = "BPF_MAP_TYPE_TASK_STORAGE")]
35+
#[derive(Debug)]
36+
pub struct TaskStorage<T, V> {
37+
pub(crate) inner: T,
38+
_v: PhantomData<V>,
39+
}
40+
41+
impl<T: Borrow<MapData>, V: Pod> TaskStorage<T, V> {
42+
pub(crate) fn new(map: T) -> Result<Self, MapError> {
43+
let data = map.borrow();
44+
check_kv_size::<u32, V>(data)?;
45+
Ok(Self {
46+
inner: map,
47+
_v: PhantomData,
48+
})
49+
}
50+
51+
/// Returns the value stored for the given `pid`.
52+
pub fn get(&self, pid: &u32, flags: u64) -> Result<V, MapError> {
53+
let pidfd = PidFd::open(*pid, 0).map_err(|(_, io_error)| SyscallError {
54+
call: "pidfd_open",
55+
io_error,
56+
})?;
57+
let map_fd = self.inner.borrow().fd().as_fd();
58+
let value = bpf_map_lookup_elem(map_fd, &pidfd.as_raw_fd(), flags).map_err(|io_error| {
59+
SyscallError {
60+
call: "bpf_map_lookup_elem",
61+
io_error,
62+
}
63+
})?;
64+
value.ok_or(MapError::KeyNotFound)
65+
}
66+
}
67+
68+
#[cfg(test)]
69+
mod tests {
70+
use std::io;
71+
72+
use assert_matches::assert_matches;
73+
use aya_obj::generated::bpf_map_type::BPF_MAP_TYPE_TASK_STORAGE;
74+
use libc::EFAULT;
75+
76+
use super::*;
77+
use crate::{
78+
maps::{
79+
Map,
80+
test_utils::{self, new_map},
81+
},
82+
sys::{SysResult, Syscall, override_syscall},
83+
};
84+
85+
fn new_obj_map() -> aya_obj::Map {
86+
test_utils::new_obj_map::<u32>(BPF_MAP_TYPE_TASK_STORAGE)
87+
}
88+
89+
fn sys_error(value: i32) -> SysResult {
90+
Err((-1, io::Error::from_raw_os_error(value)))
91+
}
92+
93+
#[test]
94+
fn test_wrong_value_size() {
95+
let map = new_map(new_obj_map());
96+
let map = Map::TaskStorage(map);
97+
assert_matches!(
98+
TaskStorage::<_, u16>::try_from(&map),
99+
Err(MapError::InvalidValueSize {
100+
size: 2,
101+
expected: 4
102+
})
103+
);
104+
}
105+
106+
#[test]
107+
fn test_try_from_wrong_map() {
108+
let map = new_map(new_obj_map());
109+
let map = Map::Array(map);
110+
assert_matches!(
111+
TaskStorage::<_, u32>::try_from(&map),
112+
Err(MapError::InvalidMapType { .. })
113+
);
114+
}
115+
116+
#[test]
117+
fn test_new_ok() {
118+
let map = new_map(new_obj_map());
119+
assert!(TaskStorage::<_, u32>::new(&map).is_ok());
120+
}
121+
122+
#[test]
123+
fn test_try_from_ok() {
124+
let map = new_map(new_obj_map());
125+
let map = Map::TaskStorage(map);
126+
assert!(TaskStorage::<_, u32>::try_from(&map).is_ok());
127+
}
128+
129+
#[test]
130+
fn test_get_pidfd_syscall_error() {
131+
let mut map = new_map(new_obj_map());
132+
let map = TaskStorage::<_, u32>::new(&mut map).unwrap();
133+
134+
override_syscall(|call| match call {
135+
Syscall::Ebpf { .. } => Ok(1),
136+
Syscall::PidfdOpen { .. } => sys_error(EFAULT),
137+
_ => sys_error(EFAULT),
138+
});
139+
140+
assert_matches!(
141+
map.get(&1, 0), Err(MapError::SyscallError(
142+
SyscallError {
143+
call: "pidfd_open",
144+
io_error
145+
}
146+
))
147+
if io_error.raw_os_error() == Some(EFAULT)
148+
);
149+
}
150+
}

aya/src/sys/mod.rs

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,22 @@ mod fake;
1010
use std::{
1111
ffi::{c_int, c_void},
1212
io,
13-
os::fd::{BorrowedFd, OwnedFd},
13+
os::fd::{AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd},
1414
};
1515

1616
use aya_obj::generated::{bpf_attr, bpf_cmd, perf_event_attr};
1717
pub(crate) use bpf::*;
1818
#[cfg(test)]
1919
pub(crate) use fake::*;
20+
use libc::pid_t;
2021
#[doc(hidden)]
2122
pub use netlink::netlink_set_link_up;
2223
pub(crate) use netlink::*;
2324
pub(crate) use perf_event::*;
2425
use thiserror::Error;
2526

27+
use crate::MockableFd;
28+
2629
pub(crate) type SysResult = Result<i64, (i64, io::Error)>;
2730

2831
#[cfg_attr(test, expect(dead_code))]
@@ -50,6 +53,10 @@ pub(crate) enum Syscall<'a> {
5053
fd: BorrowedFd<'a>,
5154
request: PerfEventIoctlRequest<'a>,
5255
},
56+
PidfdOpen {
57+
pid: pid_t,
58+
flags: u32,
59+
},
5360
}
5461

5562
/// A system call error.
@@ -90,6 +97,11 @@ impl std::fmt::Debug for Syscall<'_> {
9097
.field("fd", fd)
9198
.field("request", request)
9299
.finish(),
100+
Self::PidfdOpen { pid, flags } => f
101+
.debug_struct("Syscall::PidfdOpen")
102+
.field("pid", pid)
103+
.field("flags", flags)
104+
.finish(),
93105
}
94106
}
95107
}
@@ -137,6 +149,9 @@ fn syscall(call: Syscall<'_>) -> SysResult {
137149
),
138150
}
139151
}
152+
Syscall::PidfdOpen { pid, flags } => {
153+
libc::syscall(libc::SYS_pidfd_open, pid, flags)
154+
}
140155
}
141156
};
142157
// c_long is i32 on armv7.
@@ -235,3 +250,35 @@ impl From<Stats> for aya_obj::generated::bpf_stats_type {
235250
pub fn enable_stats(stats_type: Stats) -> Result<OwnedFd, SyscallError> {
236251
bpf_enable_stats(stats_type.into()).map(|fd| fd.into_inner())
237252
}
253+
254+
/// A file descriptor of a process.
255+
///
256+
/// A similar type is provided by the Rust standard library as
257+
/// [`std::os::linux::process`] as a nigtly-only experimental API. We are
258+
/// planning to migrate to it once it stabilizes.
259+
pub(crate) struct PidFd(MockableFd);
260+
261+
impl PidFd {
262+
pub(crate) fn open(pid: u32, flags: u32) -> Result<Self, (i64, io::Error)> {
263+
let pid_fd = pidfd_open(pid, flags)? as RawFd;
264+
let pid_fd = unsafe { MockableFd::from_raw_fd(pid_fd) };
265+
Ok(Self(pid_fd))
266+
}
267+
}
268+
269+
impl AsRawFd for PidFd {
270+
fn as_raw_fd(&self) -> RawFd {
271+
self.0.as_raw_fd()
272+
}
273+
}
274+
275+
fn pidfd_open(pid: u32, flags: u32) -> SysResult {
276+
let call = Syscall::PidfdOpen {
277+
pid: pid as pid_t,
278+
flags,
279+
};
280+
#[cfg(not(test))]
281+
return crate::sys::syscall(call);
282+
#[cfg(test)]
283+
return crate::sys::TEST_SYSCALL.with(|test_impl| unsafe { test_impl.borrow()(call) });
284+
}

test/integration-test/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ object = { workspace = true, features = ["elf", "read_core", "std"] }
3030
rand = { workspace = true, features = ["thread_rng"] }
3131
rbpf = { workspace = true }
3232
scopeguard = { workspace = true }
33+
tempfile = { workspace = true }
3334
test-case = { workspace = true }
3435
test-log = { workspace = true, features = ["log"] }
3536
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// clang-format off
2+
#include <vmlinux.h>
3+
#include <bpf/bpf_helpers.h>
4+
#include <bpf/bpf_core_read.h>
5+
#include <bpf/bpf_tracing.h>
6+
// clang-format on
7+
8+
char _license[] SEC("license") = "GPL";
9+
10+
struct {
11+
__uint(type, BPF_MAP_TYPE_TASK_STORAGE);
12+
__uint(map_flags, BPF_F_NO_PREALLOC);
13+
__type(key, int);
14+
__type(value, __u32);
15+
} task_storage SEC(".maps");
16+
17+
SEC("tp_btf/sys_enter")
18+
int BPF_PROG(sys_enter, struct pt_regs *regs, long id) {
19+
__u32 value = 1;
20+
struct task_struct *task = bpf_get_current_task_btf();
21+
bpf_task_storage_get(&task_storage, task, &value,
22+
BPF_LOCAL_STORAGE_GET_F_CREATE);
23+
24+
return 0;
25+
}

test/integration-test/build.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ fn main() -> Result<()> {
6767
("main.bpf.c", false),
6868
("multimap-btf.bpf.c", false),
6969
("reloc.bpf.c", true),
70+
("task_storage.bpf.c", true),
7071
("text_64_64_reloc.c", false),
7172
("variables_reloc.bpf.c", false),
7273
];

test/integration-test/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ pub const MULTIMAP_BTF: &[u8] =
88
pub const RELOC_BPF: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/reloc.bpf.o"));
99
pub const RELOC_BTF: &[u8] =
1010
include_bytes_aligned!(concat!(env!("OUT_DIR"), "/reloc.bpf.target.o"));
11+
pub const TASK_STORAGE: &[u8] =
12+
include_bytes_aligned!(concat!(env!("OUT_DIR"), "/task_storage.bpf.o"));
1113
pub const TEXT_64_64_RELOC: &[u8] =
1214
include_bytes_aligned!(concat!(env!("OUT_DIR"), "/text_64_64_reloc.o"));
1315
pub const VARIABLES_RELOC: &[u8] =

test/integration-test/src/tests.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ mod relocations;
1111
mod ring_buf;
1212
mod smoke;
1313
mod strncmp;
14+
mod task_storage;
1415
mod tcx;
1516
mod uprobe_cookie;
1617
mod xdp;

0 commit comments

Comments
 (0)