1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2021 Facebook */
3 
4 #include "vmlinux.h"
5 #include <bpf/bpf_helpers.h>
6 #include <bpf/bpf_tracing.h>
7 #include <bpf/bpf_core_read.h>
8 
9 /* weak and shared between two files */
10 const volatile int my_tid __weak;
11 long syscall_id __weak;
12 
13 int output_val1;
14 int output_ctx1;
15 int output_weak1;
16 
17 /* same "subprog" name in all files, but it's ok because they all are static */
18 static __noinline int subprog(int x)
19 {
20 	/* but different formula */
21 	return x * 1;
22 }
23 
24 /* Global functions can't be void */
25 int set_output_val1(int x)
26 {
27 	output_val1 = x + subprog(x);
28 	return x;
29 }
30 
31 /* This function can't be verified as global, as it assumes raw_tp/sys_enter
32  * context and accesses syscall id (second argument). So we mark it as
33  * __hidden, so that libbpf will mark it as static in the final object file,
34  * right before verifying it in the kernel.
35  *
36  * But we don't mark it as __hidden here, rather at extern site. __hidden is
37  * "contaminating" visibility, so it will get propagated from either extern or
38  * actual definition (including from the losing __weak definition).
39  */
40 void set_output_ctx1(__u64 *ctx)
41 {
42 	output_ctx1 = ctx[1]; /* long id, same as in BPF_PROG below */
43 }
44 
45 /* this weak instance should win because it's the first one */
46 __weak int set_output_weak(int x)
47 {
48 	static volatile int whatever;
49 
50 	/* make sure we use CO-RE relocations in a weak function, this used to
51 	 * cause problems for BPF static linker
52 	 */
53 	whatever = bpf_core_type_size(struct task_struct);
54 
55 	output_weak1 = x;
56 	return x;
57 }
58 
59 extern int set_output_val2(int x);
60 
61 /* here we'll force set_output_ctx2() to be __hidden in the final obj file */
62 __hidden extern void set_output_ctx2(__u64 *ctx);
63 
64 SEC("?raw_tp/sys_enter")
65 int BPF_PROG(handler1, struct pt_regs *regs, long id)
66 {
67 	static volatile int whatever;
68 
69 	if (my_tid != (u32)bpf_get_current_pid_tgid() || id != syscall_id)
70 		return 0;
71 
72 	/* make sure we have CO-RE relocations in main program */
73 	whatever = bpf_core_type_size(struct task_struct);
74 
75 	set_output_val2(1000);
76 	set_output_ctx2(ctx); /* ctx definition is hidden in BPF_PROG macro */
77 
78 	/* keep input value the same across both files to avoid dependency on
79 	 * handler call order; differentiate by output_weak1 vs output_weak2.
80 	 */
81 	set_output_weak(42);
82 
83 	return 0;
84 }
85 
86 char LICENSE[] SEC("license") = "GPL";
87