1*0fd7562aSAndrei Matei // SPDX-License-Identifier: GPL-2.0
2*0fd7562aSAndrei Matei 
3*0fd7562aSAndrei Matei #include <linux/bpf.h>
4*0fd7562aSAndrei Matei #include <bpf/bpf_helpers.h>
5*0fd7562aSAndrei Matei 
6*0fd7562aSAndrei Matei int probe_res;
7*0fd7562aSAndrei Matei 
8*0fd7562aSAndrei Matei char input[4] = {};
9*0fd7562aSAndrei Matei int test_pid;
10*0fd7562aSAndrei Matei 
11*0fd7562aSAndrei Matei SEC("tracepoint/syscalls/sys_enter_nanosleep")
probe(void * ctx)12*0fd7562aSAndrei Matei int probe(void *ctx)
13*0fd7562aSAndrei Matei {
14*0fd7562aSAndrei Matei 	/* This BPF program performs variable-offset reads and writes on a
15*0fd7562aSAndrei Matei 	 * stack-allocated buffer.
16*0fd7562aSAndrei Matei 	 */
17*0fd7562aSAndrei Matei 	char stack_buf[16];
18*0fd7562aSAndrei Matei 	unsigned long len;
19*0fd7562aSAndrei Matei 	unsigned long last;
20*0fd7562aSAndrei Matei 
21*0fd7562aSAndrei Matei 	if ((bpf_get_current_pid_tgid() >> 32) != test_pid)
22*0fd7562aSAndrei Matei 		return 0;
23*0fd7562aSAndrei Matei 
24*0fd7562aSAndrei Matei 	/* Copy the input to the stack. */
25*0fd7562aSAndrei Matei 	__builtin_memcpy(stack_buf, input, 4);
26*0fd7562aSAndrei Matei 
27*0fd7562aSAndrei Matei 	/* The first byte in the buffer indicates the length. */
28*0fd7562aSAndrei Matei 	len = stack_buf[0] & 0xf;
29*0fd7562aSAndrei Matei 	last = (len - 1) & 0xf;
30*0fd7562aSAndrei Matei 
31*0fd7562aSAndrei Matei 	/* Append something to the buffer. The offset where we write is not
32*0fd7562aSAndrei Matei 	 * statically known; this is a variable-offset stack write.
33*0fd7562aSAndrei Matei 	 */
34*0fd7562aSAndrei Matei 	stack_buf[len] = 42;
35*0fd7562aSAndrei Matei 
36*0fd7562aSAndrei Matei 	/* Index into the buffer at an unknown offset. This is a
37*0fd7562aSAndrei Matei 	 * variable-offset stack read.
38*0fd7562aSAndrei Matei 	 *
39*0fd7562aSAndrei Matei 	 * Note that if it wasn't for the preceding variable-offset write, this
40*0fd7562aSAndrei Matei 	 * read would be rejected because the stack slot cannot be verified as
41*0fd7562aSAndrei Matei 	 * being initialized. With the preceding variable-offset write, the
42*0fd7562aSAndrei Matei 	 * stack slot still cannot be verified, but the write inhibits the
43*0fd7562aSAndrei Matei 	 * respective check on the reasoning that, if there was a
44*0fd7562aSAndrei Matei 	 * variable-offset to a higher-or-equal spot, we're probably reading
45*0fd7562aSAndrei Matei 	 * what we just wrote.
46*0fd7562aSAndrei Matei 	 */
47*0fd7562aSAndrei Matei 	probe_res = stack_buf[last];
48*0fd7562aSAndrei Matei 	return 0;
49*0fd7562aSAndrei Matei }
50*0fd7562aSAndrei Matei 
51*0fd7562aSAndrei Matei char _license[] SEC("license") = "GPL";
52