|
| 1 | +#pragma once |
| 2 | + |
| 3 | +// clang-format off |
| 4 | +#include "maps.h" |
| 5 | +#include "vmlinux.h" |
| 6 | + |
| 7 | +#include <bpf/bpf_helpers.h> |
| 8 | +#include <bpf/bpf_core_read.h> |
| 9 | +// clang-format on |
| 10 | + |
| 11 | +/** |
| 12 | + * Reimplementation of the kernel d_path function. |
| 13 | + * |
| 14 | + * We should attempt to use bpf_d_path when possible, but you can't on |
| 15 | + * values that have been read using the bpf_probe_* helpers. |
| 16 | + */ |
| 17 | +__always_inline static long d_path(const struct path* path, char* buf, int buflen) { |
| 18 | + if (buflen <= 0) { |
| 19 | + return -1; |
| 20 | + } |
| 21 | + |
| 22 | + struct helper_t* helper = get_helper(); |
| 23 | + if (helper == NULL) { |
| 24 | + return -1; |
| 25 | + } |
| 26 | + |
| 27 | + struct task_struct* task = (struct task_struct*)bpf_get_current_task(); |
| 28 | + int offset = (buflen - 1) & (PATH_MAX - 1); |
| 29 | + helper->buf[offset] = '\0'; // Ensure null termination |
| 30 | + |
| 31 | + struct path root; |
| 32 | + BPF_CORE_READ_INTO(&root, task, fs, root); |
| 33 | + struct mount* mnt = container_of(path->mnt, struct mount, mnt); |
| 34 | + struct dentry* dentry = BPF_CORE_READ(path, dentry); |
| 35 | + |
| 36 | + for (int i = 0; i < 16 && (dentry != root.dentry || &mnt->mnt != root.mnt); i++) { |
| 37 | + struct dentry* parent = BPF_CORE_READ(dentry, d_parent); |
| 38 | + struct dentry* mnt_root = BPF_CORE_READ(mnt, mnt.mnt_root); |
| 39 | + |
| 40 | + if (dentry == mnt_root) { |
| 41 | + struct mount* m = BPF_CORE_READ(mnt, mnt_parent); |
| 42 | + if (m != mnt) { |
| 43 | + dentry = BPF_CORE_READ(mnt, mnt_mountpoint); |
| 44 | + mnt = m; |
| 45 | + continue; |
| 46 | + } |
| 47 | + break; |
| 48 | + } |
| 49 | + |
| 50 | + if (dentry == parent) { |
| 51 | + return -1; |
| 52 | + } |
| 53 | + |
| 54 | + struct qstr d_name; |
| 55 | + BPF_CORE_READ_INTO(&d_name, dentry, d_name); |
| 56 | + int len = d_name.len; |
| 57 | + if (len <= 0 || len >= buflen) { |
| 58 | + return -1; |
| 59 | + } |
| 60 | + |
| 61 | + offset -= len; |
| 62 | + if (offset <= 0) { |
| 63 | + return -1; |
| 64 | + } |
| 65 | + |
| 66 | + if (bpf_probe_read_kernel(&helper->buf[offset], len, d_name.name) != 0) { |
| 67 | + return -1; |
| 68 | + } |
| 69 | + |
| 70 | + offset--; |
| 71 | + if (offset <= 0) { |
| 72 | + return -1; |
| 73 | + } |
| 74 | + helper->buf[offset] = '/'; |
| 75 | + |
| 76 | + dentry = parent; |
| 77 | + } |
| 78 | + |
| 79 | + bpf_probe_read_str(buf, buflen, &helper->buf[offset]); |
| 80 | + return buflen - offset; |
| 81 | +} |
0 commit comments