Skip to content

Commit 182a811

Browse files
committed
rex/task_struct: update get_comm method
Signed-off-by: MinhPhan8803 <[email protected]>
1 parent e7bb614 commit 182a811

File tree

1 file changed

+11
-19
lines changed

1 file changed

+11
-19
lines changed

rex/src/task_struct.rs

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::bindings::linux::kernel::task_struct;
2-
use crate::bindings::uapi::linux::errno::EINVAL;
32
use crate::per_cpu::{current_task, this_cpu_read};
43
use crate::pt_regs::PtRegs;
4+
use core::ffi::{self as core_ffi, CStr};
55

66
// Bindgen has problem generating these constants
77
const TOP_OF_KERNEL_STACK_PADDING: u64 = 0;
@@ -43,27 +43,19 @@ impl TaskStruct {
4343
self.kptr.tgid
4444
}
4545

46-
// Design decision: the original BPF interface does not have type safety,
47-
// since buf is just a buffer. But in Rust we can use const generics to
48-
// restrict it to only [u8; N] given that comm is a cstring. This also
49-
// automatically achieves size check, since N is a constexpr.
50-
pub fn get_comm<const N: usize>(&self, buf: &mut [i8; N]) -> i32 {
51-
if N == 0 {
52-
return -(EINVAL as i32);
53-
}
54-
55-
let size = core::cmp::min::<usize>(N, self.kptr.comm.len()) - 1;
56-
if size == 0 {
57-
return -(EINVAL as i32);
58-
}
59-
60-
buf[..size].copy_from_slice(&self.kptr.comm[..size]);
61-
buf[size] = 0;
62-
0
46+
// Design decision: the equivalent BPF helper writes the program name to
47+
// a user-provided buffer, here we can take advantage of Rust's ownership by
48+
// just providing a &CStr instead
49+
pub fn get_comm(&self) -> Result<&CStr, core_ffi::FromBytesUntilNulError> {
50+
// casting from c_char to u8 is sound, see:
51+
// https://doc.rust-lang.org/src/core/ffi/c_str.rs.html#264
52+
let comm_bytes =
53+
unsafe { &*(&self.kptr.comm[..] as *const _ as *const [u8]) };
54+
CStr::from_bytes_until_nul(comm_bytes)
6355
}
6456

6557
pub fn get_pt_regs(&self) -> &'static PtRegs {
66-
// X86 sepcific
58+
// X86 specific
6759
// stack_top is actually bottom of the kernel stack, it refers to the
6860
// highest address of the stack pages
6961
let stack_top =

0 commit comments

Comments
 (0)