1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2020 Facebook */
3 #include "bpf_iter.h"
4 #include <bpf/bpf_helpers.h>
5 
6 char _license[] SEC("license") = "GPL";
7 
8 #define MAX_STACK_TRACE_DEPTH   64
9 unsigned long entries[MAX_STACK_TRACE_DEPTH] = {};
10 #define SIZE_OF_ULONG (sizeof(unsigned long))
11 
12 SEC("iter/task")
dump_task_stack(struct bpf_iter__task * ctx)13 int dump_task_stack(struct bpf_iter__task *ctx)
14 {
15 	struct seq_file *seq = ctx->meta->seq;
16 	struct task_struct *task = ctx->task;
17 	long i, retlen;
18 
19 	if (task == (void *)0)
20 		return 0;
21 
22 	retlen = bpf_get_task_stack(task, entries,
23 				    MAX_STACK_TRACE_DEPTH * SIZE_OF_ULONG, 0);
24 	if (retlen < 0)
25 		return 0;
26 
27 	BPF_SEQ_PRINTF(seq, "pid: %8u num_entries: %8u\n", task->pid,
28 		       retlen / SIZE_OF_ULONG);
29 	for (i = 0; i < MAX_STACK_TRACE_DEPTH; i++) {
30 		if (retlen > i * SIZE_OF_ULONG)
31 			BPF_SEQ_PRINTF(seq, "[<0>] %pB\n", (void *)entries[i]);
32 	}
33 	BPF_SEQ_PRINTF(seq, "\n");
34 
35 	return 0;
36 }
37 
38 SEC("iter/task")
get_task_user_stacks(struct bpf_iter__task * ctx)39 int get_task_user_stacks(struct bpf_iter__task *ctx)
40 {
41 	struct seq_file *seq = ctx->meta->seq;
42 	struct task_struct *task = ctx->task;
43 	uint64_t buf_sz = 0;
44 	int64_t res;
45 
46 	if (task == (void *)0)
47 		return 0;
48 
49 	res = bpf_get_task_stack(task, entries,
50 			MAX_STACK_TRACE_DEPTH * SIZE_OF_ULONG, BPF_F_USER_STACK);
51 	if (res <= 0)
52 		return 0;
53 
54 	buf_sz += res;
55 
56 	/* If the verifier doesn't refine bpf_get_task_stack res, and instead
57 	 * assumes res is entirely unknown, this program will fail to load as
58 	 * the verifier will believe that max buf_sz value allows reading
59 	 * past the end of entries in bpf_seq_write call
60 	 */
61 	bpf_seq_write(seq, &entries, buf_sz);
62 	return 0;
63 }
64