1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2021 Google LLC. */
3 
4 #include <linux/bpf.h>
5 #include <bpf/bpf_helpers.h>
6 #include <bpf/bpf_tracing.h>
7 
8 __u32 pid = 0;
9 
10 char num_out[64] = {};
11 long num_ret = 0;
12 
13 char ip_out[64] = {};
14 long ip_ret = 0;
15 
16 char sym_out[64] = {};
17 long sym_ret = 0;
18 
19 char addr_out[64] = {};
20 long addr_ret = 0;
21 
22 char str_out[64] = {};
23 long str_ret = 0;
24 
25 char over_out[6] = {};
26 long over_ret = 0;
27 
28 char pad_out[10] = {};
29 long pad_ret = 0;
30 
31 char noarg_out[64] = {};
32 long noarg_ret = 0;
33 
34 long nobuf_ret = 0;
35 
36 extern const void schedule __ksym;
37 
38 SEC("raw_tp/sys_enter")
39 int handler(const void *ctx)
40 {
41 	/* Convenient values to pretty-print */
42 	const __u8 ex_ipv4[] = {127, 0, 0, 1};
43 	const __u8 ex_ipv6[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
44 	static const char str1[] = "str1";
45 	static const char longstr[] = "longstr";
46 
47 	if ((int)bpf_get_current_pid_tgid() != pid)
48 		return 0;
49 
50 	/* Integer types */
51 	num_ret  = BPF_SNPRINTF(num_out, sizeof(num_out),
52 				"%d %u %x %li %llu %lX",
53 				-8, 9, 150, -424242, 1337, 0xDABBAD00);
54 	/* IP addresses */
55 	ip_ret   = BPF_SNPRINTF(ip_out, sizeof(ip_out), "%pi4 %pI6",
56 				&ex_ipv4, &ex_ipv6);
57 	/* Symbol lookup formatting */
58 	sym_ret  = BPF_SNPRINTF(sym_out,  sizeof(sym_out), "%ps %pS %pB",
59 				&schedule, &schedule, &schedule);
60 	/* Kernel pointers */
61 	addr_ret = BPF_SNPRINTF(addr_out, sizeof(addr_out), "%pK %px %p",
62 				0, 0xFFFF00000ADD4E55, 0xFFFF00000ADD4E55);
63 	/* Strings embedding */
64 	str_ret  = BPF_SNPRINTF(str_out, sizeof(str_out), "%s %+05s",
65 				str1, longstr);
66 	/* Overflow */
67 	over_ret = BPF_SNPRINTF(over_out, sizeof(over_out), "%%overflow");
68 	/* Padding of fixed width numbers */
69 	pad_ret = BPF_SNPRINTF(pad_out, sizeof(pad_out), "%5d %0900000X", 4, 4);
70 	/* No args */
71 	noarg_ret = BPF_SNPRINTF(noarg_out, sizeof(noarg_out), "simple case");
72 	/* No buffer */
73 	nobuf_ret = BPF_SNPRINTF(NULL, 0, "only interested in length %d", 60);
74 
75 	return 0;
76 }
77 
78 char _license[] SEC("license") = "GPL";
79