1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2020 Facebook */
3 #include "bpf_iter.h"
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_tracing.h>
6 
7 char _license[] SEC("license") = "GPL";
8 
9 uint32_t tid = 0;
10 int num_unknown_tid = 0;
11 int num_known_tid = 0;
12 
13 SEC("iter/task")
14 int dump_task(struct bpf_iter__task *ctx)
15 {
16 	struct seq_file *seq = ctx->meta->seq;
17 	struct task_struct *task = ctx->task;
18 	static char info[] = "    === END ===";
19 
20 	if (task == (void *)0) {
21 		BPF_SEQ_PRINTF(seq, "%s\n", info);
22 		return 0;
23 	}
24 
25 	if (task->pid != tid)
26 		num_unknown_tid++;
27 	else
28 		num_known_tid++;
29 
30 	if (ctx->meta->seq_num == 0)
31 		BPF_SEQ_PRINTF(seq, "    tgid      gid\n");
32 
33 	BPF_SEQ_PRINTF(seq, "%8d %8d\n", task->tgid, task->pid);
34 	return 0;
35 }
36 
37 int num_expected_failure_copy_from_user_task = 0;
38 int num_success_copy_from_user_task = 0;
39 
40 SEC("iter.s/task")
41 int dump_task_sleepable(struct bpf_iter__task *ctx)
42 {
43 	struct seq_file *seq = ctx->meta->seq;
44 	struct task_struct *task = ctx->task;
45 	static const char info[] = "    === END ===";
46 	struct pt_regs *regs;
47 	void *ptr;
48 	uint32_t user_data = 0;
49 	int ret;
50 
51 	if (task == (void *)0) {
52 		BPF_SEQ_PRINTF(seq, "%s\n", info);
53 		return 0;
54 	}
55 
56 	/* Read an invalid pointer and ensure we get an error */
57 	ptr = NULL;
58 	ret = bpf_copy_from_user_task(&user_data, sizeof(uint32_t), ptr, task, 0);
59 	if (ret) {
60 		++num_expected_failure_copy_from_user_task;
61 	} else {
62 		BPF_SEQ_PRINTF(seq, "%s\n", info);
63 		return 0;
64 	}
65 
66 	/* Try to read the contents of the task's instruction pointer from the
67 	 * remote task's address space.
68 	 */
69 	regs = (struct pt_regs *)bpf_task_pt_regs(task);
70 	if (regs == (void *)0) {
71 		BPF_SEQ_PRINTF(seq, "%s\n", info);
72 		return 0;
73 	}
74 	ptr = (void *)PT_REGS_IP(regs);
75 
76 	ret = bpf_copy_from_user_task(&user_data, sizeof(uint32_t), ptr, task, 0);
77 	if (ret) {
78 		BPF_SEQ_PRINTF(seq, "%s\n", info);
79 		return 0;
80 	}
81 	++num_success_copy_from_user_task;
82 
83 	if (ctx->meta->seq_num == 0)
84 		BPF_SEQ_PRINTF(seq, "    tgid      gid     data\n");
85 
86 	BPF_SEQ_PRINTF(seq, "%8d %8d %8d\n", task->tgid, task->pid, user_data);
87 	return 0;
88 }
89