1// SPDX-License-Identifier: GPL-2.0
2/* Copyright (C) 2021. Huawei Technologies Co., Ltd */
3#include <stdbool.h>
4#include <linux/types.h>
5#include <linux/bpf.h>
6#include <bpf/bpf_helpers.h>
7#include <bpf/bpf_tracing.h>
8
9#define STRNCMP_STR_SZ 8
10
11const char target[STRNCMP_STR_SZ] = "EEEEEEE";
12char str[STRNCMP_STR_SZ];
13int cmp_ret = 0;
14int target_pid = 0;
15
16const char no_str_target[STRNCMP_STR_SZ] = "12345678";
17char writable_target[STRNCMP_STR_SZ];
18unsigned int no_const_str_size = STRNCMP_STR_SZ;
19
20char _license[] SEC("license") = "GPL";
21
22SEC("?tp/syscalls/sys_enter_nanosleep")
23int do_strncmp(void *ctx)
24{
25 if ((bpf_get_current_pid_tgid() >> 32) != target_pid)
26 return 0;
27
28 cmp_ret = bpf_strncmp(str, STRNCMP_STR_SZ, target);
29 return 0;
30}
31
32SEC("?tp/syscalls/sys_enter_nanosleep")
33int strncmp_bad_not_const_str_size(void *ctx)
34{
35 /* The value of string size is not const, so will fail */
36 cmp_ret = bpf_strncmp(str, no_const_str_size, target);
37 return 0;
38}
39
40SEC("?tp/syscalls/sys_enter_nanosleep")
41int strncmp_bad_writable_target(void *ctx)
42{
43 /* Compared target is not read-only, so will fail */
44 cmp_ret = bpf_strncmp(str, STRNCMP_STR_SZ, writable_target);
45 return 0;
46}
47
48SEC("?tp/syscalls/sys_enter_nanosleep")
49int strncmp_bad_not_null_term_target(void *ctx)
50{
51 /* Compared target is not null-terminated, so will fail */
52 cmp_ret = bpf_strncmp(str, STRNCMP_STR_SZ, no_str_target);
53 return 0;
54}
55

source code of linux/tools/testing/selftests/bpf/progs/strncmp_test.c