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