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