|
1 | 1 | use crate::bindings::linux::kernel::task_struct; |
2 | | -use crate::bindings::uapi::linux::errno::EINVAL; |
3 | 2 | use crate::per_cpu::{current_task, this_cpu_read}; |
4 | 3 | use crate::pt_regs::PtRegs; |
| 4 | +use core::ffi::{self as core_ffi, CStr}; |
5 | 5 |
|
6 | 6 | // Bindgen has problem generating these constants |
7 | 7 | const TOP_OF_KERNEL_STACK_PADDING: u64 = 0; |
@@ -43,27 +43,19 @@ impl TaskStruct { |
43 | 43 | self.kptr.tgid |
44 | 44 | } |
45 | 45 |
|
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) |
63 | 55 | } |
64 | 56 |
|
65 | 57 | pub fn get_pt_regs(&self) -> &'static PtRegs { |
66 | | - // X86 sepcific |
| 58 | + // X86 specific |
67 | 59 | // stack_top is actually bottom of the kernel stack, it refers to the |
68 | 60 | // highest address of the stack pages |
69 | 61 | let stack_top = |
|
0 commit comments